Arrow Functions: Basics
Introduction
Arrow functions introduced in ES6 is a concise way of creating functions compared to function expressions.
The name arrow function comes from the use of =>
.
Syntax:
const functionName = (arg1, arg2, ... argN) => {
return value;
}
Example
const multiply = (a, b) => {
return a * b;
}
console.log(multiply(7, 8)); // 56
console.log(multiply(3, 2)); // 6
Key Features
- Arrow functions are anonymous function until they are assigned to a variable.
- If there is only 1 argument, we can skip parenthesis
const square = x => { return x * x; } console.log(square(2)); // 4 console.log(square(7)); // 49
The only caveat to this rule is that if the 1 argument is destructured.
const foo = ({name = "New User"}) => name; console.log(foo({})); // New User console.log(foo({name: "Parwinder"})); // Parwinder
- If there is no arguments, we need to have the parenthesis
const greeting = () => { return "Hello World!"; } console.log(greeting()); // Hello World!
- If the function body is an expression, it will return the expression, we can remove the brackets and the return keyword.
const greeting = () => "Hello World!"; console.log(greeting()); // Hello World
Now that we know all these key features, let us rewrite the example to get the square of a number:
const square = x => x * x;
console.log(square(4)); // 16