Functions
A block that groups processing together so it can be reused.
Function declarations
// Function declaration
function greet(name) {
return `Hello, ${name}!`;
}
// Calling the function
console.log(greet("Taro")); // Hello, Taro!
Function expressions
This is the style of assigning a function to a variable.
// Function expression (anonymous function)
const add = function(a, b) {
return a + b;
};
console.log(add(5, 3)); // 8
Arrow functions (ES6)
A syntax that lets you write functions more concisely.
// Arrow function - a more concise style
const multiply = (a, b) => a * b;
console.log(multiply(4, 2)); // 8
// A multi-line arrow function
const divide = (a, b) => {
if (b === 0) {
return "Cannot divide by zero";
}
return a / b;
};
console.log(divide(10, 2)); // 5
console.log(divide(10, 0)); // Cannot divide by zero
An arrow function inherits the this of the place where it is defined as is (lexical this). The this of a regular function, on the other hand, changes depending on "how it is called." The convenient thing about arrow functions is that this doesn't shift when you pass them as a callback.
However, an arrow function does not have an arguments object and is not suited to being an object method. Also, calling it with new causes an error, so it can't be used as a constructor. Use the right one for the situation.
Default parameters (ES6)
You can specify an initial value for when an argument isn't passed.
function welcome(name = "Guest") {
return `Welcome, ${name}!`;
}
console.log(welcome()); // Welcome, Guest!
console.log(welcome("Hanako")); // Welcome, Hanako!
The rest syntax (ES6)
Receives a variable number of arguments as an array.
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 15
Older code used the arguments object for variadic arguments, but today the rest syntax like ...numbers is recommended. Arguments received with the rest syntax are a real array, so you can use array methods such as map and reduce (which you'll learn about in detail in Arrays) directly, and they work in arrow functions too.
What to read next
- Objects — Group related data and processing together