*
Previous Javascript-Functions Functions, Parameters & Scope in JavaScript Next

Arrow Functions in JavaScript

📘 Arrow Functions in JavaScript

1️⃣ What is an Arrow Function?

An arrow function is a concise way to write functions using the => syntax. They are always expressions (not declarations) and are often used for shorter functions.

They were introduced in ES6 (2015) and are a shorter, cleaner way to write function expressions.

2️⃣ Syntax

// Traditional function expression
const add1 = function(a, b) {
  return a + b;
};

// Arrow function
const add2 = (a, b) => {
  return a + b;
};

// Even shorter (implicit return for single expression)
const add3 = (a, b) => a + b;
  

3️⃣ Examples

Without Parameters

const greet = () => "Hello World!";
console.log(greet()); // Hello World!
  

With One Parameter

const square = x => x * x;
console.log(square(5)); // 25
  

With Multiple Parameters

const multiply = (a, b) => a * b;
console.log(multiply(3, 4)); // 12
  

Returning an Object

const makeUser = (name, age) => ({ name: name, age: age });
console.log(makeUser("Alice", 25)); 
// { name: "Alice", age: 25 }
  

4️⃣ Key Differences from Regular Functions

  • No own this → Arrow functions inherit this from their surrounding scope.
  • No arguments object → They don’t have their own arguments.
  • Not hoisted → Must be defined before use.
  • Cannot be used as constructors → You can’t use new with arrow functions.

5️⃣ Example: this Behavior

function Person() {
  this.age = 0;

  // Using arrow function → 'this' refers to Person
  setInterval(() => {
    this.age++;
    console.log(this.age);
  }, 1000);
}

new Person(); // increments age correctly
  

✅ Quick Recap

  • Arrow functions are shorter and cleaner.
  • Great for callbacks and small functions.
  • They don’t have their own this or arguments.
  • Not suitable for object methods or constructors.

📌 Mini Project: Double Numbers

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
  

Use Cases of Arrow Functions

  • Callbacks: Useful for concise functions in map, filter, forEach, etc.
    let numbers = [1, 2, 3];
    let squares = numbers.map(n => n * n);
    console.log(squares); // [1, 4, 9]
  • Short utility functions: Ideal for one-liner operations.
    const add = (a, b) => a + b;
    console.log(add(5, 3)); // 8
  • No this binding: Great for preserving this inside methods or event handlers.
    function Counter() {
    this.count = 0;
    setInterval(() => {
    this.count++;
    console.log(this.count);
    }, 1000);
    }
    new Counter();
  • Functional programming: Works well in chaining methods and clean functional-style code.
  • Use arrow functions for short callbacks and function expressions.
Back to Index
Previous Javascript-Functions Functions, Parameters & Scope in JavaScript Next
*
*