Arrow function VS function in JavaScript

Arrow function VS function in JavaScript

ES5 has introduced the arrow function in JavaScript. There are some differences between normal function and arrow function. I will discuss the difference in this blog.

Syntax

Normal function syntax

function person (){
// code
}

Arrow function syntax

const person =()=>{
//code
}

this keyword

  • The arrow function doesn't have its own this. this is binded to the most parent value. For example, this will be more clear.
const person = {
    name: "ab",
    age: () => {
        console.log(this);
    },
    age2: function () {
        console.log(this);
    }

}

person.age(); //{}
person.age2();//{ name: 'ab', age: [Function: age], age2: [Function: age2] }

Now, try to understand the above code. In the person object, there are two methods. One of them is the arrow function and the rest is the normal function. Both of them are doing the same thing but the outputs are not the same. Why?

Because this in the arrow function pointed to the most parent value. In this code, most parent value is the global object. That is the reason, it is printed empty object.

If you run this code in the browser console, then you get this.

Screen Shot 2022-03-31 at 5.19.19 PM.png

On the other hand, this in normal function pointed to the current previous value.

Constructor

new keyword is not working in the arrow function when you create a new instance.

// normal function

function Person(age) {
    this.age = age;
}
const info = new Person('23');
console.log(info); // Person { age: '23' }
// arrow function
const Person = (age) => {
    this.age = age;
}
const info = new Person('23');
console.log(info); //TypeError: Person is not a constructor

Hosting

The arrow function doesn't allow hoisting.

person()
function person() {
    console.log("hello"); // hello
}
//arrow function
person();

const person = () => { // same for var or let
    console.log('hello'); // ReferenceError: Cannot access 'person' before initialization
}

Return value

An arrow function doesn't need the return keyword in one line return value.

//arrow function
const person = (a) => (a * a);
console.log(person(2)); //4
//normal function
function person(a) { a * a}

console.log(person(2));