1
function sum() {
    return this.a + this.b;
} 

This function should find the values of a and b from the global scope and then add them together if there is no call. At first I set a = 3, b = 4;. If I then type sum() I get 7. If I update The values of a and b without declaring them to const. The value of this.a and this.b is reflected in sum().

But when I type const a = 10; and then go ahead and run sum() it's value is still 7. Shouldn't the value be 14? I'm doing these calculations on console in google chrome if that matters.

sample screenshot of the console

Shouldn't the value of sum() be 13 now that a = 5? why is it still using the old value of a?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Don't use `this.a` to access a global variable, just use `a`. `this.a` will only work if the function is defined in sloppy mode, if it is called without a context, and the `.a` is actually a property of the global object (which `let`- and `const`-declared variables are not). – Bergi Apr 26 '21 at 01:56

0 Answers0