Hacker News new | past | comments | ask | show | jobs | submit login

No, GP is correct. If you omit the `var` (or `let`/`const` in es6) then you are implicitly assigning a property on the global object (`window` in the browser), in essence setting a global variable. Never omit `var`.

If you are in a function scope, `var` declarations are hoisted to the top of the function scope, outside of any block scope, as you described. `let` and `const` declarations from es6 are block scoped. Personally I highly recommend never using `var` and simply adopting es6 and using `let` and `const`, preferring `const`, everywhere as they have significantly simpler and more intuitive semantics.




I agree with the way you've responded. But there can be a case where omitting var on a variable definition will not assign it on the global object. That is, if you hit a variable by the same name as you go up the scope stack, you will just overwrite that variable's value. Example:

  function f1(){
    var v = 'val';
    var f2 = function(){
      v = 'inner'; // will not hit global scope
    }
    f2();
    console.log(v);
  }

  f1();
  console.log(v);

output:

  val
  Uncaught ReferenceError: v is not defined




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: