Understanding arrow functions in javascript

Arrow functions, introduced in ECMAScript 6 (ES6), provide a concise syntax for writing functions in JavaScript. They offer a shorter and more readable alternative to traditional function expressions. 

Basic Arrow Function:

In this example, the arrow function add takes two parameters a and b and returns their sum. The concise syntax (a, b) => a + b represents the function body.

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

 console.log(add(2, 3)); // Output: 5

Arrow Function with No Parameters:

Here, the arrow function greet takes no parameters and directly returns the string "Hello!".

 const greet = () => "Hello!";

 console.log(greet()); // Output: Hello!

Arrow Function with a Single Parameter:

The arrow function square takes a single parameter num and returns its square.

 const square = num => num * num;

 console.log(square(5)); // Output: 25

Arrow Function with Multiple Parameters:

This example shows an arrow function multiply with multiple parameters  enclosed in curly braces {}. The result variable is assigned the product of a and b, and then it is returned.

   const multiply = (a, b) => {

    const result = a * b;

    return result;

   };

  console.log(multiply(4, 5)); // Output: 20

Arrow Function as a Callback - Using Arrow Functions with Array Methods

Here, the map function applies the arrow function num => num * num to each element of the numbers array, returning a new array squaredNumbers with the squares of the original elements.  Arrow functions are often used with array methods like map, filter, and reduce to provide concise and readable code for iterating over arrays.

 const numbers = [1, 2, 3, 4, 5];

 const squaredNumbers = numbers.map(num => num * num);

 console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]

Arrow Function with this Context:

Arrow functions don't bind their own this context but inherit it from the surrounding scope.

In this example, the arrow function within setInterval uses the this context of the Person object. The arrow function increments the age property of Person every second.

 function Person() {

    this.age = 0;

    setInterval(() => {

      this.age++;

      console.log(this.age);

    }, 1000);

   }

   const person = new Person();

   // Output: 1, 2, 3, 4, ...

Implicit Return:

When the arrow function has a single expression, the curly braces and return statement can be omitted. The expression is evaluated and implicitly returned.

 const square = (num) => num * num;

 console.log(square(5)); // Output: 25

Object Literal:

Arrow functions can also return object literals. To avoid ambiguity with function bodies, the object literal needs to be wrapped in parentheses

 const getPerson = (name, age) => ({ name, age });

 console.log(getPerson("John", 30)); 

// Output: { name: 'John', age: 30 }