0

function main() {
    a = 5;
    b = 10;
    console.log(a + b);
}
main();                 //prints 15
console.log(a + b);     //prints 15

JavaScript supports functional and global scoping yet the second console.log statement prints the output 15. If i use var to declare the variables then the second console.log throws error. I am still learning JavaScript coming from a c++/java background this seems very confusing.

  • _"...yet the second console.log statement prints the output 15"_ - Because `a` and `b` are global variables because of the missing `var` – Andreas Jul 24 '20 at 08:51
  • Welcome to [*The Horror of Implicit Globals*](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html). Use strict mode. There **has** to be a dupetarget for this... – T.J. Crowder Jul 24 '20 at 08:52
  • Yes, always put `"use strict";` at the top of your JavaScript file to avoid issues like this. – Michael Geary Jul 24 '20 at 08:54

0 Answers0