Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, can I use a variable before it is declared?

I have been wondering for a while if I can use a variable in JS before it is defined, such as the following:

var country = "USA";
switch (country) {
    case "USA":
        country = i;
    case "blach":
        //not finished yet
}
/*
  put a whole
  bunch more code here
*/
var i = 10;

Is this valid? Is it allowed? And if so, what is the technical term for it?

like image 666
tjons Avatar asked Nov 26 '13 15:11

tjons


People also ask

Can we use variable without declaring?

We can use strict mode which is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a “strict” operating context. It will throw Reference error : x is not defined, when we assign a value to a variable without declaring it. Example 4: Javascript.

What happens when you assign a variable that hasn't been declared yet?

Undeclared variables are undefined because they simply do not exist. As described earlier, assigning a value to an undeclared variable does not cause an error; instead, it implicitly declares the variable in the global scope.


3 Answers

This is a technique used by the JavaScript engine called hoisting. The parser will read through the entire function before running it, and any variable declarations (i.e. using the var keyword) will be executed as if they were at the top of the containing scope. So your code behaves like:

var country;
var i;

country = "USA";
switch (country) {
case "USA":
    country = i;
case "blach":
    //not finished yet
}

i = 10;

So, i is declared throughout the entire scope, but its value is undefined until the i = 10 statement runs.

In ECMAScript terms, when a function is invoked, the function's new lexical scope builds its VariableEnvironment before any of the function's code runs. In ECMAScript 10.5, step 8:

8. For each VariableDeclaration... d in code, in source text order do

a. Let dn be the Identifier in d.

...

i. Call env’s CreateMutableBinding concrete method passing dn and configurableBindings as the arguments.

ii. Call env’s SetMutableBinding concrete method passing dn, undefined, and strict as the arguments.

This is quite a mouthful, but basically it says:

Before you run a function, look through the function's source code for declarations like var [identifierName].

For each declaration you find, create a new variable in the function's scope with the name [identifierName] used in the declaration and then set its value to undefined

like image 97
apsillers Avatar answered Sep 22 '22 01:09

apsillers


It's called variable hoisting, and it's a good concept to understand as it can occasionally create bugs that are hard to track down.

For example:

var stuff = 'stuff';
function() {
 console.log(stuff); //outputs 'undefined'
 var stuff = 'other stuff';
 console.log(stuff); //outputs 'other stuff'
}

The first console.log outputs undefined because the var stuff in the function was hoisted to the top of the function.

//theoretical compiled output
var stuff = 'stuff';
function() {
 var stuff; //has not been defined
 console.log(stuff);
 stuff = 'other stuff'; //defined here
 console.log(stuff);
}

Without knowledge of variable hoisting, this result may be confusing.

For this reason, if you look at professionally developed JavaScript code, typically you'll see all variables in a function are declared at the top.

like image 27
adamb Avatar answered Sep 22 '22 01:09

adamb


Yes. In JavaScript, variables are hoisted

A variable statement declares variables that are created as defined in 10.5. Variables are initialised to undefined when created. A variable with an Initialiser is assigned the value of its AssignmentExpression when the VariableStatement is executed, not when the variable is created.ES5 §12.2
Where 10.5 step 8 is the part of interest

like image 3
Moritz Roessler Avatar answered Sep 22 '22 01:09

Moritz Roessler