Arrow Function vs Normal Function in JavaScript

MAK STYLE 119
2 min readMar 29, 2023

--

Arrow Function vs Normal Function in JavaScript

In JavaScript, there are two types of functions: normal functions and arrow functions. While they both accomplish the same task, they have some differences in their syntax, behavior, and use cases. In this blog post, we’ll compare arrow functions and normal functions in JavaScript and discuss their similarities and differences.

Syntax:

The syntax of arrow functions is more concise than that of normal functions. In an arrow function, the function keyword is replaced by the => operator, and there are no curly braces or return keyword required for a single-line function. For example, here's a normal function that adds two numbers:

function addNumbers(a, b) {
return a + b;
}

And here’s the same function as an arrow function:

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

As you can see, the arrow function is more concise and requires fewer characters.

Behavior:

The behavior of arrow functions is slightly different than that of normal functions. One key difference is that arrow functions do not have their own this keyword. Instead, they inherit the this value of the enclosing lexical context. In contrast, normal functions have their own this keyword, which can be bound to different values depending on how the function is called. This can lead to unexpected behavior when using normal functions, especially when dealing with object methods or event handlers.

Use Cases:

Arrow functions are generally recommended for simple, one-line functions that don’t require a lot of complex logic or context. They are particularly useful for writing inline functions, such as in array methods like map, filter, and reduce. For example, here's how you could use an arrow function with map to square each number in an array:

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

In contrast, normal functions are better suited for more complex logic or when you need access to the this keyword. For example, if you need to define an object method, you would typically use a normal function to ensure that the this keyword is bound correctly:

const myObj = {
name: "John",
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
}

Conclusion:

In summary, arrow functions and normal functions both serve the same purpose of defining functions in JavaScript, but have some differences in their syntax, behavior, and use cases. Arrow functions are more concise and useful for simple, one-line functions, while normal functions are better suited for more complex logic or when you need access to the this keyword. By understanding these differences, you can choose the right type of function for your specific use case and write more efficient and maintainable code.

--

--

MAK STYLE 119

Anime and manga lover | Coding | JavaScript | Rust | always with error | MAKSTYLE119 | 03/06/2022 | 😵