Functions- Building Blocks of JavaScript

Functions- Building Blocks of JavaScript

Arrow Functions in JavaScript: A Simpler Way to Write Functions

Arrow functions (=>) were introduced in ES6 (ECMAScript 2015)

what ?

Arrow functions allow us to write shorter function syntax which is easy to read and write.

Before the arrow function we were used to were writing the traditional function like as ..

const add = function (a, b) {
  return a + b;
};
console.log(add(2, 3)); // Output: 5

But after the arrow function introduced we write the function like that .

const add = (a, b) => {
    return  a + b;
}
console.log(add(2, 3)); // Output: 5

If the function has only one statement, and the statement returns a value, you can remove the brackets and the return keyword:

const add = (a+b) => a+b;
console.log(add)

In fact if you have one input you can remove parentheses as well called Implicit Return.

Implicit Return (ES6)

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

What About this keyword ?

One of the major advantages of arrow functions is that they don’t create their own this. Instead, they inherit this from the surrounding scope.

Handling of this is also different in arrow functions compared to regular functions

In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever.

With arrow functions the this keyword always represents the object that defined the arrow function.

Problem with this in ES5

With a regular function this represents the object that calls the function.

eg-0

// Regular Function:
hello = function() {
  document.getElementById("demo").innerHTML += this;
}

// The window object calls the function:
window.addEventListener("load", hello);

// A button object calls the function:
document.getElementById("btn").addEventListener("click", hello);

eg-1

function Person(name) {
  this.name = name;
  setTimeout(function () {
    console.log(this.name); // `this` refers to the global object, not `Person`
  }, 1000);
}
new Person("Himanshu");

Fixed with Arrow Function

With an arrow function this represents the owner of the function.

eg-0

// Arrow Function:
hello = () => {
  document.getElementById("demo").innerHTML += this;
}

// The window object calls the function:
window.addEventListener("load", hello);

// A button object calls the function:
document.getElementById("btn").addEventListener("click", hello);

eg-1

function Person(name) {
  this.name = name;
  setTimeout(() => {
    console.log(this.name); // Now `this` correctly refers to `Person`
  }, 1000);
}
new Person("Himanshu"); // Output: Himanshu

Arrow functions became popular for use in array methods like map, filter, and reduce.

const numbers = [1, 2, 3, 4, 5];
const squared = numbers.map(n => n * n);
console.log(squared); // Output: [1, 4, 9, 16, 25]

No arguments Object in ES6

Arrow functions don’t have their own arguments object like regular functions.

Regular function

function showArgs() {
  console.log(arguments);
}
showArgs(1, 2, 3); // Output: [1, 2, 3]

Arrow Function (No arguments)

const showArgs = () => {
  console.log(arguments); // Error: arguments is not defined
};
showArgs(1, 2, 3);

If you need arguments, you must use rest parameters:

const showArgs = (...args) => console.log(args);
showArgs(1, 2, 3); // Output: [1, 2, 3]

Arrow Functions in Classes

With ES6, arrow functions became useful in classes when dealing with event handlers.

Without Arrow Function (Problem)

class Button {
  constructor() {
    this.label = "Click Me";
  }
  handleClick() {
    console.log(this.label); // Error: `this` is undefined
  }
}
const btn = new Button();
document.getElementById("myButton").addEventListener("click", btn.handleClick);

With Arrow Function (Fix)

class Button {
  constructor() {
    this.label = "Click Me";
  }
  handleClick = () => {
    console.log(this.label); // Correctly logs "Click Me"
  };
}
const btn = new Button();
document.getElementById("myButton").addEventListener("click", btn.handleClick);

Evolution in Modern JavaScript

  • Arrow functions are now widely used in React (JSX), functional programming, and modern JavaScript frameworks.

  • The combination of async/await and arrow functions has made asynchronous code much cleaner.

      const fetchData = async () => {
        const response = await fetch("https://api.example.com/data");
        const data = await response.json();
        console.log(data);
      };
    

Limitations and When to Avoid Arrow Functions

Methods inside objects (because they don’t bind this)

const obj = {
  name: "Himanshu",
  greet: () => console.log(`Hello, ${this.name}`) // `this` is undefined
};
obj.greet();