Google Chrome and Firebug give me two different outputs with this example.
if b gets global, then first should give me undefined and second one 14. right? but in firebug, it gives two 14s and Chrome gives reference error.
function a() {
b = 14;
}
console.log(b);
a();
console.log(b);
It will throw Reference error : x is not defined, when we assign a value to a variable without declaring it.
If you don't declare a variable explicitly, JavaScript will declare it implicitly for you.
If you declare a variable, without using "var", the variable always becomes GLOBAL.
Variables can be declared and initialize without the var keyword. However, a value must be assigned to a variable declared without the var keyword. The variables declared without the var keyword becomes global variables, irrespective of where they are declared.
Don't use the browser console for scope experiments. Different browser consoles run your code in different ways.
If you run that code exactly as quoted in a normal environment, the correct thing is that you'll get a ReferenceError
from the first console.log(b)
line:
function a() {
b = 14;
}
console.log(b); // ReferenceError
a();
console.log(b);
Even in loose mode, trying to read the value of an undeclared identifier is a ReferenceError
.
If we remove that initial console.log
, we'd be in an area that varies depending on loose vs. strict mode:
// In loose mode
function a() {
b = 14;
}
a();
console.log(b); // 14
That's The Horror of Implicit Globals;1 in loose mode, assigning to an undeclared identifier creates a global variable.
Vs.
// In strict mode
"use strict";
function a() {
b = 14; // ReferenceError
}
a();
console.log(b);
...which is how it should be.
1That's a post on my anemic little blog.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With