es6

Chapter 4: Arrow Functions in JavaScript (ES6) Made Easy

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

  1. Create an arrow function called triple that multiplies a number by 3 and returns the result.
  2. Rewrite this function using arrow syntax:
    
    function greet(name) {
      return "Hi, " + name + "!";
    }
          
  3. Given an array [3, 5, 7], use map() with an arrow function to return each element squared.
  4. Create a multi-line arrow function that takes two numbers, logs them, and returns their sum.

Leave a Reply

Your email address will not be published. Required fields are marked *