Chrome console: the difference between 'let' and 'var'?

I attached an animated gif to illustrate this strange behavior. Essentially, my question is, does Chrome handle the var and let console differently when used in the same area? You will notice that after declaring / assigning a variable, if you try to enter the name of this variable in the console, Chrome will automatically close it for you, showing a drop-down list containing what you are typing. Using let s is not the case. Is this a bug, a function, or is there something I miss in var and let in JavaScript?

Note. I am well aware that let lives and dies in the immediate area.

enter image description here

+6
source share
2 answers

When you use var in the console, it runs in the global scope and adds a variable to the window object.

When you use let in the console, it runs in a global scope that does not add a variable to the window object.

When you start typing, autocomplete checks the parent object for properties to complete, along with other language constructs such as function , for and while .

If there is no content in the console, the parent window object that will not have the property you are looking for because let does not add the property to window .

As soon as you have a new object to complete autocomplete, the behavior will return to what you expect.

 > let foo = {bar: 'baz'}; > foo.b //autocompletes bar 

Now, with all that has been said, there is no reason why autocomplete should behave this way. In many ways, the lack of autocomplete for variables globally defined with let can be considered a β€œmistake” worth a β€œcommit”. In my opinion, this is a moderately surprising behavior.

+9
source

var defines a variable in the global scope, and let defines it only in the local scope. Most likely, autocomplete considers only global possibilities for goals.

+1
source

All Articles