stckpete
stckpete

Reputation: 571

Global Variable in JavaScript , variables defined without var

The function below will return b is not defined because the compiler will look in the function and then into the global scope in search for a variable b.

However, I assumed that defining b without the word var would automatically create a global variable?

Can anyone explain the rules when omitting the word var?

function foo(a) {    
  console.log( a + b );    
  b = a;
}

foo( 2 );

Upvotes: 1

Views: 126

Answers (3)

Scott Marcus
Scott Marcus

Reputation: 65806

Not using var in a function for a variable declaration does make it global, but in your case, the JavaScript engine is hitting this line:

console.log( a + b );

before it hits this line:

b = a;

And, that's the line that declares it (globally).

And, because you didn't use var, the declaration is not hoisted to the top of the code base (which it would have been with var - you would still not have gotten a value for b because only the declaration would be hoisted, not the initialization, but it would not have thrown an error), so you get your error.

See more about var and hoisting here.

Upvotes: 4

groooves
groooves

Reputation: 470

Variables declared this way b = a are not hoisted, like variables declared with the var keyword. That means that, at runtime, the compiler reads b, not as undefined (as would happen with var b = a), but as something that doesn´t exist at all, thus throwing a ReferenceError.

Info on Hoisting: https://developer.mozilla.org/en-US/docs/Glossary/Hoisting

Upvotes: 0

Quentin
Quentin

Reputation: 943569

In strict mode:

  • Using an undeclared variable will throw an exception

In non-strict mode:

  • Assigning to an undeclared variable will create a global, but this is not hoisted
    • Declaring a variable with var creates a local variable and is hoisted to the top of the function
  • Reading an undeclared variable will throw an exception

Since you are not in strict mode and you try to read b before you assign a value to it, you get an exception.


Guidelines to follow:

  • Always "use strict"
  • Always declare your variables
  • Declare them in the global scope if you want them there
  • … but try to avoid global scope. Consider using a closure instead if you think a global would be useful.

Upvotes: 1

Related Questions