23

Ok, my question is simple: In JavaScript / ES6

what happens when you have something like

 x = 5;

 console.log(x);  // 5

is the interpreter automatically adding "let" at runtime or why is this working without errors?




Edit: Strict Mode The syntax of ES5 allowed for something called implicit globals, which have been the source of many frustrating programming errors. In short, if you forgot to declare a variable with var , JavaScript would merrily assume you were referring to a global variable. If no such global variable existed, it would create one! You can imagine the problems this caused.

I see. Thank you for all comments. I now understand why is this happening. Thanks!

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Combine
  • 3,894
  • 2
  • 27
  • 30

4 Answers4

14

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/

Ben Aston
  • 53,718
  • 65
  • 205
  • 331
xcodebuild
  • 1,121
  • 9
  • 17
2

In this case, x becomes a global variable. Try to avoid this as global variables can be hard on the browser.

Bálint
  • 4,009
  • 2
  • 16
  • 27
1

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

Ben
  • 3,160
  • 3
  • 17
  • 34
1

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.

Pierre.Vriens
  • 2,117
  • 75
  • 29
  • 42