A function is a reusable block of code that groups a sequence of statements together to perform a specific task.
A function declaration consists of the following:
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
To call a function in your code, you type the function name followed by parentheses.
For example
function hello() {
console.log("Hello");
}
hello();
To return a value from a function, we use a return statement.
function add(num1, num2) {
return num1 + num2;
}
console.log(add(3,4)); // 7
We can set a default value for the parameter with the keyword =
.
function add(num1 = 1, num2 = 2) {
return num1 + num2;
}
console.log(add()); // 3
The rest parameter allows us to represent an indefinite number of arguments as an array.
const sum = (function () {
return function sum(...args) {
return args.reduce((a, b) => a + b, 0);
};
})();
console.log(sum(1, 2, 3));
is similar to:
const sum = (function () {
return function sum(x, y, z) {
const args = [x, y, z];
return args.reduce((a, b) => a + b, 0);
};
})();
console.log(sum(1, 2, 3));