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?