1

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 );
2
  • 1
    it is because of console.log there b is not defined. Commented Dec 20, 2016 at 15:25
  • 1
    it does, yes but you're trying to use the variable b before you've defined it, of you move the console.log to after b=a; it will return 4 Commented Dec 20, 2016 at 15:26

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.