Reputation: 4214
In JavaScript / ES6.
What happens when you have something like:
x = 5;
console.log(x); // 5
Is the interpreter automatically adding let
at runtime? Why is this working without errors?
Upvotes: 26
Views: 14001
Reputation: 81
then you're not declaring/defining a variable; instead you're creating/defining (or overwriting) some global/window obj property
x = 5;
is the same as
window.x = 5;
You can check it with window
, or with the this
keyword in your browser console; look at the global/window obj properties, you'll see the x
property there.
Upvotes: 1
Reputation: 1221
By omitting let
, const
, or var
in non-strict mode, you create a property on the global object.
By the way, babel
will add "use strict";
by default. So you will get a error with babel
.
You can try it here: https://babeljs.io/repl/
Upvotes: 16
Reputation: 3654
Adding to the previous two answers:
Assignment without the keyword returns the value:
> const x = 4
undefined
> let y = 4
undefined
> var z = 4
undefined
> a = 4
4
And dropping the keyword is used in some minifiers to cutdown on payload
Upvotes: 1
Reputation: 4039
In this case, x becomes a global variable. Try to avoid this as global variables can be hard on the browser.
Upvotes: 2