Gyaan

Arrow Functions

beginner ES6 functions

Introduced in ES6, arrow functions allow us to write shorter function syntax:

let myFunction = (a, b) => a * b;

The most important difference is that arrow functions do not have their own this. They take this from the parent scope where they are defined.

const person = {
  name: "Manish",
  greetRegular: function() {
    console.log(this.name); // "Manish" (this refers to person)
  },
  greetArrow: () => {
    console.log(this.name); // undefined (this refers to parent/window scope)
  }
};

If there is only one parameter, we can skip the parentheses. If the body is a single expression, we can also skip the curly braces and return keyword — the value is returned automatically.

const double = x => x * 2;

const add = (a, b) => a + b;

const getUser = () => ({ name: "Manish" }); // wrap object in () for implicit return

Arrow functions cannot be used as constructors, which means we cannot use new keyword with them — it will throw a TypeError.