Search code examples
javascriptscopethisarrow-functionslexical

What forms a scope in javascript?


While reading about 'this' keyword and arrow function, I read: that arrow functions binds to whatever execution context the surrounding scope has. I have attached a simple code example below. When I tried:

const user = {
  firstName: "John",
  sayHi() {
    console.log("this in normal function", this);
    console.log(`Hello, ${this.firstName}!`);
  },
  sayHiWithArrow: () => {
    console.log("This in arrow function", this);
    console.log(`Hello, ${this.firstName} with Arrow!`);
  },
};

user.sayHi();
user.sayHiWithArrow();

in console for the arrow function in nodejs environment :

"This in arrow function {}"
Hello, undefined with Arrow!

My question is isnt scope anything that is in {} blocks, which in this case is user object? I would like to know what forms a scope in javascript, Why isnt the object's {} considered a scope here?


Solution

  • Why isnt the object's {} considered a scope here?

    {} has several unrelated meaning in JavaScript:

    • blocks, which define scope (functions, for loops, etc)
    • object literals

    Your example is an object literal. That's why it doesn't behave like a block.