difference between normal function and arrow function 1

difference between normal function and arrow function

//* main difference is arrow functions do not have their own this
let user = {
  name: "HEllo world",
  functTest() {
    console.log("----functTest---", this.name) // HEllo world
  },
  arrowTest: () => { 
    console.log("----arrowTest----", this.name) // undefined
  }
}
user.functTest()
user.arrowTest()

Here is what the above code is Doing:
1. We create an object called user.
2. We add a function called functTest to the user object.
3. We add an arrow function called arrowTest to the user object.
4. We call the functTest function.
5. We call the arrowTest function.

When we call the functTest function, it prints out “HEllo world”.
When we call the arrowTest function, it prints out “undefined”.

Why does the arrowTest function print out “undefined”?

The reason is because arrow functions do not have their own this.

When we call the functTest function, this.name is “HEllo world”.
When we call the arrowTest function, this.name is undefined.

The arrowTest function is using the this from the global scope.

In the global scope, this.name is undefined.

Similar Posts