Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Two output when not using var keyword

Tags:

javascript

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);
like image 764
Meysam Avatar asked Nov 05 '16 11:11

Meysam


People also ask

What happens if you assign a variable without any keyword in JavaScript?

It will throw Reference error : x is not defined, when we assign a value to a variable without declaring it.

What happens if you don't declare a variable in JavaScript?

If you don't declare a variable explicitly, JavaScript will declare it implicitly for you.

How does variable behave without VAR?

If you declare a variable, without using "var", the variable always becomes GLOBAL.

What happens if you assign a variable without a keyword?

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.


1 Answers

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.

like image 114
T.J. Crowder Avatar answered Nov 10 '22 21:11

T.J. Crowder