DEV Community

Dainwi Kumar
Dainwi Kumar

Posted on

JavaScript Normal Functions vs Arrow Functions

Are you curious about the difference between normal functions and arrow functions in JavaScript? Let's explore this concept in simple terms!

In JavaScript, functions are blocks of code designed to perform a particular task. There are two main types: normal functions and arrow functions.

Normal functions:

function greet(name) {
  return "Hello, " + name + "!";
}
Enter fullscreen mode Exit fullscreen mode

Normal functions are defined using the function keyword followed by the function name and parameters. They have their own this value which is determined by how they are called.

Arrow functions:

const greet = (name) => {
  return "Hello, " + name + "!";
};
Enter fullscreen mode Exit fullscreen mode

Arrow functions are a more concise way to write functions introduced in ES6. They use the arrow => to separate the parameters from the function body. Unlike normal functions, arrow functions do not have their own this value. Instead, they inherit the this value from the enclosing lexical context.

Let's see the difference in usage:

Normal function:

const person = {
  name: "Alice",
  greet: function() {
    return "Hello, " + this.name + "!";
  }
};
Enter fullscreen mode Exit fullscreen mode

Arrow function:

const person = {
  name: "Alice",
  greet: () => {
    return "Hello, " + this.name + "!";
  }
};
Enter fullscreen mode Exit fullscreen mode

In the normal function example, this.name refers to the name property of the person object. However, in the arrow function example, this.name will be undefined because arrow functions do not have their own this binding.

In summary, normal functions and arrow functions have similar functionalities, but differ in syntax and behavior, particularly with regards to the this keyword. Understanding these differences can help you choose the right type of function for your JavaScript code!

And that's it! You've just learned about the difference between normal functions and arrow functions in JavaScript. Happy coding! πŸš€

Top comments (0)