JavaScript functions are an essential part of the language, allowing you to define reusable blocks of code. Functions can help you organize your code, make it more readable, and maintainable.
Basic Syntax
The basic syntax for a JavaScript function is as follows:
function functionName(parameters) {
// code to be executed
}
Types of Functions
There are two types of functions in JavaScript:
Built-in Functions: These are functions that are provided by JavaScript itself. Examples include
alert()
,parseInt()
, andMath.random()
.User-Defined Functions: These are functions that you create yourself. They can be used to perform specific tasks that are not provided by built-in functions.
Example
Here is an example of a user-defined function that calculates the sum of two numbers:
function addNumbers(a, b) {
return a + b;
}
console.log(addNumbers(5, 3)); // Outputs: 8
Parameters and Arguments
Functions can accept parameters, which are values passed into the function. These parameters are defined in the function's parentheses.
function greet(name) {
console.log('Hello, ' + name + '!');
}
greet('Alice'); // Outputs: Hello, Alice!
In the above example, name
is a parameter. When we call greet('Alice')
, Alice
is passed as an argument.
Return Values
Functions can also return values. The return
statement is used to specify the value that the function should return.
function multiply(a, b) {
return a * b;
}
console.log(multiply(4, 3)); // Outputs: 12
Arrow Functions
Arrow functions are a newer addition to JavaScript. They provide a more concise syntax for writing functions.
const greet = (name) => {
console.log('Hello, ' + name + '!');
};
greet('Bob'); // Outputs: Hello, Bob!
Further Reading
For more information on JavaScript functions, please visit our JavaScript Functions Guide.