Arrow Functions

Arrow functions are a concise way to write JavaScript functions introduced in ES6 (ECMAScript 2015). They offer a shorter syntax compared to traditional function definitions. Here’s a breakdown of arrow functions with examples:

Simple Arrow Function:

This is the most basic form, where you have an argument and an implicit return statement (meaning the return keyword is not required).

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

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

Arrow Function with Multiple Parameters:

You can have multiple parameters just like regular functions.

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

console.log(add(3, 4)); // Output: 7
const isEven = (num) => {
  if (num % 2 === 0) {
    return true;
  } else {
    return false;
  }
};

console.log(isEven(10)); // Output: true

Arrow Functions as Callbacks:

Arrow functions are commonly used as callbacks in functions like map, filter, etc.

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((num) => num * 2);

console.log(doubled); // Output: [2, 4, 6, 8, 10]

Key points to remember:

  • Arrow functions are always anonymous (they don’t have a name).
  • They cannot be used as constructors.
  • Arrow functions have implicit this binding, which can be different from traditional functions.

I hope this explanation clarifies arrow functions!