Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 var and let 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 lets, this is not the case. Is this a bug, feature, or is there something I'm missing about var and let in JavaScript?

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

enter image description here

like image 827
The Qodesmith Avatar asked Sep 08 '16 17:09

The Qodesmith


2 Answers

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.

like image 50
zzzzBov Avatar answered Sep 27 '22 22:09

zzzzBov


var defines a variable on the global scope, while let defines it only in the local scope. Most likely, the autocomplete is only looking on the global scope for targets.

like image 37
Soviut Avatar answered Sep 27 '22 22:09

Soviut