0

The following code I run in three different ways but only one works without errors. I don't understand why. Could you please tell me if not window who does keep reference to the variable?

SCRIPT:

'use strict';

let s = function(){};

TRY 1**********************************

s();

CONSOLE: OK

TRY 2**********************************

window.s();

CONSOLE: ERROR

TypeError: window.s is not a function

TRY 3**********************************

this.s();

CONSOLE: ERROR

TypeError: this.s is not a function


  • 1
    [That's just how `let` works](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let). It's in the scope of the file, why would it need to be a property of some object? – Thomas Jul 08 '20 at 16:01
  • Related: [Do let statements create properties on the global object?](https://stackoverflow.com/q/28776079/4642212). – Sebastian Simon Jul 08 '20 at 16:20

2 Answers2

0

let doesn't create a property of window.

Just like const the let does not create properties of the window object when declared globally (in the top-most scope) MDN.

0

let can be only available inside the scope it's declared (scope to the block) use var , which defines a variable globally ....

Try

'use strict';
var s = function(){};

'use strict';

var  s = function(){};
// TRY 1**********************************

s();

// TRY 2**********************************

window.s();


// TRY 3**********************************

this.s();
BLAYTI Ribh
  • 71
  • 1
  • 9