0

I am a noob to programming and i am trying to understand 'this' keyword. so i defined a variable in global scope and i was expecting that if i use such a variable with 'this' keyword in a function defined and called in global scope, function would return value of the variable which was assinged in global scope. but i am getting undefined

`

let title = "global";

const func = () => {
  const title = "func";

  console.log(this);
  console.log(this.title);
};

func();

` console show window object and undefined

  • 1
    `let` statements don't attach variables as properties to the global object. The variable is only accessible as `title`, not as property of anything. – deceze Dec 02 '22 at 11:02
  • The duplicate contains the answer to the problem, but note that you shouldn't really be using globals in the first place. – Rory McCrossan Dec 02 '22 at 11:02
  • I agree with @Rory McCrossan about not using globals. But if you need to use it absolutely the way you described use `var` instead of `let`. – er.bhargav.vyas Dec 02 '22 at 11:06

0 Answers0