-2

When we create a variable without specifying let or var it gets added to window object in browser. For example

function change(){
    val = 20;
}
change();
console.log(window.val); //20
console.log(val);  //20

Here I am getting both console logs print value 20. But I do the same using let it doesn't get added to window object. I saw this answer with the explanation why this is happening.

let val = 20;
console.log(window.val); //undefined
console.log(val); //20

Now, in the below code, can someone explain, when I assign an un scoped variable inside the function why it is not getting added to window scope? Instead how it is changing the value of the variable declared with let

let value = 10;
function change(){
    value = 20;
}
change();
console.log(window.value); //undefined 
console.log(value); //20  why this is 20?
Vineesh
  • 3,762
  • 20
  • 37

2 Answers2

2

MDN says this about var:

The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global. If you re-declare a JavaScript variable, it will not lose its value.

MDN says this about let:

Variables declared by let have their scope in the block for which they are defined, as well as in any contained sub-blocks. In this way, let works very much like var. The main difference is that the scope of a var variable is the entire enclosing function:

They both end up in a scope which is then propagated to child scopes but which scope they end up in and how they go about determining that scope is different.

Note that the entirety of a <script> element does have an implicit block and this implicit block inherits window as an ancestor scope. Variable declared by var end up scoped into window while variables declared by let are scoped into this implicit block.

Ouroborus
  • 16,237
  • 4
  • 39
  • 62
0

Declaring variables with let in the top-level of your script lets you access it inside your entire script and even outside. Inside your function, you are not assigning a value to an unscoped variable.

Even if you were to write your function as below, it would not assign to the window object as it would then be function scoped.

function change(){
var value = 20;
}