0

As these two discussions says:

javascript global variable with 'var' and without 'var' [duplicate]

Difference between using var and not using var in JavaScript

There should be no different when global variable with 'var' or not.

However, the following two snips of code get different results.

First One:

if(h == undefined){
  h = 4;
}

Second One:

if(h == undefined){
  var h = 4;
}

With the first one, I will get the error message: "ReferenceError: h is not defined."

However the second one is fine.

The really weird thing is that var h = 4; is after h == undefined but it let global variable can be initialized somehow.

Community
  • 1
  • 1
Tom
  • 13
  • 2

2 Answers2

0

You need to initialize the variable h outside of the block for desired result ... Javascript have no block scope . But not works always fine said by D. Crockford

Ashisha Nautiyal
  • 1,389
  • 2
  • 19
  • 39
0

As Musa pointed out, JS performs variable declarations first (within the context you are in). so if you ever define a variable with var inside your context, it will be known, with a value of undefined. Since you should declare your variables anyway instead of relying on the global scope, you should always use the second one. If you want to use the first one for a particular reason, you can write it like this:

if (window.h === undefined) {
    h = 4;
}
Levi
  • 2,103
  • 14
  • 9