🧁Arrow Functions

In JavaScript, an arrow function (also known as a "fat arrow function") is a shorthand way to define a function. Arrow functions have a shorter syntax compared to regular functions and also have a lexical this binding.

The basic syntax of an arrow function is as follows:

(param1, param2, …) => { statements }

or

param1 => statement

Here's an example of an arrow function that takes two parameters, x and y, and returns their sum:

let add = (x, y) => {
  return x + y;
}
console.log(add(3, 4)); // Output: 7

If the arrow function only has one parameter, the parentheses can be omitted:

let square = x => x * x;
console.log(square(5)); // Output: 25

If the arrow function only has one statement, the curly braces and the return keyword can be omitted:

let double = x => x * 2;
console.log(double(5)); // Output: 10

Arrow functions also have a lexical this binding, which means that the this keyword inside an arrow function refers to the this of the surrounding scope, rather than the object on which the function is called. This can be useful in situations where the this keyword would normally be unpredictable. For example, when you use a function as a callback, the this keyword inside that function might not be what you expect.

Here's an example of an arrow function being used as a callback:

let obj = {
  name: "John",
  printName: function() {
    setTimeout(() => {
      console.log(this.name);
    }, 1000);
  }
};
obj.printName(); // Output: "John" after 1 second

Arrow functions have a shorter syntax, making them easier to read, and have a lexical this binding, which makes them useful in situations where the this keyword would normally be unpredictable, such as when using functions as callbacks. However, they cannot be used as constructors and don't have a prototype property.

Last updated