The Qodesmith The Qodesmith - 1 month ago 5
Javascript Question

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

I've attached an animated gif to illustrate this weird behavior. Essentially, my question is does Chrome console treat

differently when used in the same scope? You'll notice that after declaring / assigning a variable, if you try to type that variable's name into the console, Chrome will autocomplete it for you, showing a dropdown list containing what your typing. When using
s, this is not the case. Is this a bug, feature, or is there something I'm missing about
in JavaScript?

Note: I'm well aware that
lives & dies within the immediate scope.

enter image description here


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

When you use let in the console, it executes in the global scope, which doesn't add the 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.

When there is no content in the console, the parent object is window, which won't have the property you're looking for because let doesn't add the property to window.

As soon as you have a new object for autocomplete to complete, behavior returns to what you'd expect.

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

Now, with all of that said, there's no reason that autocomplete has to behave that way. In many regards the lack of autocomplete for variables defined in global scope via let could be considered a "bug" worth "fixing". In my opinion it is moderately surprising behavior.