Arrow functions in Javascript explained

Arrow functions, also known as "fat arrow" functions, are a more concise syntax for writing function expressions in JavaScript. They were introduced in ECMAScript 6, and have become a popular feature of the language.

Here is a simple example of an arrow function:

const greet = name => `Hello, ${name}!`;

console.log(greet('John')); // Output: "Hello, John!"

In this example, the greet function takes a single argument name, and returns a string that greets the person by name. Notice that the function is defined using the const keyword, followed by the function name, and then the function body is enclosed in parentheses. This syntax is known as the "concise body" syntax for arrow functions.

If the function body consists of a single expression, then the value of that expression is automatically returned. In the example above, the expression 'Hello, ' + name + '!' is returned.

Arrow functions can also have a block body, in which case you need to use the return keyword to specify the value that should be returned. Here's an example of an arrow function with a block body:

const add = (a, b) => {
  return a + b;
};

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

In this example, the add function takes two arguments a and b, and returns their sum. The function body is enclosed in curly braces, and the return statement is used to specify the value that should be returned.

One of the main benefits of using arrow functions is that they lexically bind the this value. This means that the value of this inside an arrow function is the same as the value of this in the surrounding code. Here's an example that demonstrates this:

const person = {
  name: 'John',
  greet: function() {
    setTimeout(() => {
      console.log(`Hello, my name is ${this.name}`);
    }, 1000);
  }
};

person.greet(); // Output: "Hello, my name is John" (after 1 second)

In this example, the person object has a name property and a greet method. The greet method uses setTimeout to delay the greeting by one second. Inside the callback function for setTimeout, we use an arrow function to log the greeting to the console. Notice that we use this.name to reference the name property of the person object.

Because the arrow function lexically binds the this value, the value of this inside the arrow function is the same as the value of this in the surrounding greet method. This means that the name property is correctly accessed, and the output is "Hello, my name is John".

I hope this gives you a good understanding of arrow functions in JavaScript. If you have any questions, feel free to ask!

That's it.

Did you find this article valuable?

Support Eirik Madland by becoming a sponsor. Any amount is appreciated!