JavaScript Arrow Functions Tutorial
What are the arrow functions?
- Arrow functions are a easiest and modern way to write JavaScript functions. They are defined using the => operator.
- These are works like a regular functions but syntax is different.
// Regular function
function add(a, b) {
return a + b;
}
let addResult = add(9,8);
console.log(addResult); // 17
// Arrow function
const sum = (a, b) => a + b;
let sumResult = sum(9,8)
console.log(sumResult); // 17
// Both functions are equivalent and will return the same result.
If the function body is more than one expression we should use curly braces {}.
const sum = sum(a, b) =>{
let add = a + b;
return add;
}
let result = sum(9, 5);
console.log(result); // 14
When to use arrow functions in JavaScript
- Arrow functions are a good choice for short, simple functions.
- Arrow functions are also a good choice for functions that are passed to other functions as arguments.
- Arrow functions are not a good choice for functions that need to bind their own this keyword.
// Arrow functions can be used to create simple functions:
const greet = (name) => `Hello, ${name}!`;
// Arrow functions can be used to create anonymous functions:
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map((number) => number * 2);
// Arrow functions can be used to pass functions to other functions as arguments:
const filterEvenNumbers = (numbers) => numbers.filter((number) => number % 2 === 0);
const evenNumbers = filterEvenNumbers([1, 2, 3, 4, 5]);