Functions are one of the fundamental building blocks in JavaScript. A function is a reusable block of code that performs a specific task. It can accept input in the form of parameters and can return a value.
Here's an example of a simple function that adds two numbers:
function add(a, b) {
return a + b;
}
In this example, add
is the name of the function, and a
and b
are the parameters. The function returns the sum of a
and b
.
To call this function, you can simply use the function name followed by the arguments in parentheses:
var sum = add(5, 10);
console.log(sum); // Output: 15
This code calls the add
function with arguments of 5
and 10
. The function returns 15
, which is then assigned to the sum
variable. The console.log
statement then outputs the value of sum
.
Functions can also be defined using function expressions or arrow functions. Here's an example of a function expression:
var multiply = function(a, b) {
return a * b;
};
And here's an example of an arrow function:
var subtract = (a, b) => {
return a - b;
};
Both of these functions work the same way as the add
function, but are defined using different syntax.