-2

in this i didn't defined now variable but when i run code in console it is working why?

var year, yearJohn, yearMark;
now = 2018
year = 2018;
yearJohn = year - 28;
yearMark = year - 33;
console.log(yearJohn, yearMark);
console.log(now + 2);

i expect the output of code will be syntax error, but the actual outpur is 2020.

adiga
  • 34,372
  • 9
  • 61
  • 83
  • Those variables get defined in the current context. It is similar to debugging JS code where you can add new variables. Like you defined now as 2018 and added 2 so the output is 2020 – Sagar Agrawal Sep 25 '19 at 16:37
  • You have `now = 2018`, and in non-strict mode, variable assignments with no prior declaration will automatically cause said variable to be added to the global context. Running the code in strict-mode will cause a `ReferenceError`. – ASDFGerte Sep 25 '19 at 16:38
  • You don't have to manually add each line with with *"enter code here"*. Please read: [How do I format my code blocks?](https://meta.stackexchange.com/questions/22186) and [How do I create a runnable stack snippet?](https://meta.stackoverflow.com/questions/358992) – adiga Sep 25 '19 at 16:41

1 Answers1

0

See MDN documentation for var

Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed.

Carsten
  • 21
  • 2