Skip to main content

Command Palette

Search for a command to run...

JavaScript Arrow Functions: A Simpler Way to Write Functions

Updated
2 min read

Before arrow functions were introduced to JavaScript, to write functions we had to use the function keyword. But due to that the code looked cluttered and less readable compared to the arrow functions because it introduced new coding style and improved readability.

What are arrow functions ?

Arrow functions are a shorter way to write function expressions in JavaScript. They are called arrow functions because they use the => symbol to point from the parameters to the body of the function.

The transformation: Normal to Arrow

Lets see how both the functions look

  • Traditional Function
function hello() {
    console.log("Hello World");
}
  • Arrow Function
const greet = (name) => {
    return `Hello ${name}`;
}

The functions might look readable right now but the traditional one creates more clutter while writing bigger functions.

Arrow Functions with 2 parameters

Now how do we add more parameters to the arrow functions ?

Here is how you do it

const addNumbers = (a,b,c,d) {
    return a+b+c+d;
}

const sum = addNumbers(1,2,3,4);
console.log(sum); // Output: 10

Implicit vs Explicit returns

This is where the arrow functions shine.

  • Implicit return
const square = (n) => n**n;
  • Explicit return
const double = (n) => {
    return 2n;
}

Implicit return helps in single line functions to be short and readable rather than using braces and then write the return keyword to return the result.

Basic difference between normal and arrow functions

In a normal function the this keyword is dynamic. It changes depending on how the function is called. If you are inside an object, this points to the object. If you call it in the global scope, this points to the window/global object.

On the other hand, the arrow functions do not have their own this. Instead, they inherit this from the code that surrounds them (their "Lexical" scope).

Thank You

With this, the blog comes to an end. I hope this blog was helpful to make you understand the difference between arrow function and normal functions and their usecases.