Reputation: 1770
I am trying to understand variable scopes in Javascript and a friend asked me this question. I could use some help here.
function abc(){
var a = b = 10; // a is local, b is global variable. Right?
c = 5; // c is global variable
}
d = 20; // d is global variable
console.log(b); // b is not defined error. Why? Isn't b a global variable?
console.log(c); // Again, Why is 'c not defined'.
I ran this code in chrome console. Shouldn't I expect 10 and 5 in console? It gives a 'b is not defined', 'c is not defined' error instead. Why does this happen if b, c are global variables? console.log(d) works just fine.
Here's a fiddle.
Upvotes: 1
Views: 158
Reputation: 2612
EDIT: This is why I love SO, you learn something knew even when you're a know it all and answer questions you clearly are not equipped to answer. Thanks to @FelixKling's clarification I have updated this to reflect that
var
s
So there's a little bit of a terminology confusion going on here:
Javascript has function level scope: as a
and b
are declared inside the function
block they are local to the function
they were declared within and are constrained to the function
's scope.
Variables defined outside a function (or in a browser on the window
object, in node on the global
object), have global
scope.
So the var
keyword doesn't actually have anything to do with global
scope, scope is defined by where you declare a variable.
Taking your example:
function abc(){
var a = b = 10; //a is local, b is global (see @FelixKling's answer)
c = 5; // c is global as it is not prefixed with the `var` keyword
}
var d = 20; // d is global
console.log(a); // logs "10" to the console
console.log(b); // b is not defined
console.log(c); // 'c not defined'.
console.log(d); // logs 20 to the console.
Upvotes: 1
Reputation: 816452
Why does this happen if
b
,c
are global variables?
b
and c
are only created if you actually call abc
. Merely defining the function does not magically execute its body.
function abc(){
var a = b = 10; // a is local, b is global variable.
c = 5; // c is global variable
}
// call abc to execute the statements inside the function
abc();
console.log(b); // 10
console.log(c); // 5
That said, implicitly creating global variables is not good still. Avoid globals if possible, and if not, explicitly declare them by assigning to the global object (window
in browsers).
Upvotes: 4