Arrow Functions in JavaScript (ES6)
Arrow functions (also called fat arrow functions) were introduced in ES6 to make writing functions shorter and simpler. They help reduce code length and are especially useful when writing inline or callback functions.
π What Makes Arrow Functions Special?
- No need to use the
function
keyword - If thereβs only one statement, you can skip curly braces
{}
- If thereβs only one return value, you donβt need the
return
keyword - They automatically bind
this
from the parent scope (more on that later)
π§ͺ Example 1: Traditional vs Arrow Function
// Traditional Function
function multiply(a, b) {
return a * b;
}
// Arrow Function
const multiply = (a, b) => a * b;
console.log(multiply(4, 3)); // Output: 12
π¦ Example 2: Single Parameter and Implicit Return
const square = n => n * n;
console.log(square(5)); // Output: 25
Note: If there is only one parameter, parentheses ()
can be omitted.
π Example 3: Arrow Function with Multiple Lines
const greetUser = (name) => {
const greeting = `Hello, ${name}!`;
return greeting;
};
console.log(greetUser("Anjali")); // Output: Hello, Anjali!
Note: Curly braces and return
are needed when using multiple lines.
π Example 4: Using Arrow Functions with Arrays
let scores = [65, 80, 45];
let doubled = scores.map(score => score * 2);
console.log(doubled); // Output: [130, 160, 90]
This is one of the most common real-life uses of arrow functions β working with arrays like map
, filter
, and sort
.
π Summary
() =>
is the new way to write functions in ES6- Shorter syntax, especially useful in callbacks
- No
this
binding headaches inside arrow functions - Use
const
when declaring arrow functions to avoid accidental changes
π Assignments: Practice Arrow Functions
- Create an arrow function called
triple
that multiplies a number by 3 and returns the result. - Rewrite this function using arrow syntax:
function greet(name) { return "Hi, " + name + "!"; }
- Given an array
[3, 5, 7]
, usemap()
with an arrow function to return each element squared. - Create a multi-line arrow function that takes two numbers, logs them, and returns their sum.