The Qodesmith
The Qodesmith

Reputation: 3375

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

Upvotes: 6

Views: 1343

Answers (2)

zzzzBov
zzzzBov

Reputation: 179046

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.

Upvotes: 9

Soviut
Soviut

Reputation: 91525

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.

Upvotes: 1

Related Questions