Javascript var declaration scope

Introduction

The var operator defined variable is local to the function scope where it was defined.

Defining a variable inside of a function using var means that the variable is destroyed as the function exits:

function test() { 
   var message = "hi";  // local variable 
} 
test(); 
console.log(message); // error! 

Here, the message variable is defined within a function using var.

The function test() creates the variable and assigns its value.

After that, the variable is destroyed so the last line causes an error.

We can define a variable globally by omitting the var operator as follows:

function test() { 
   message = "hi";  // global variable 
} 
test(); 
console.log(message); // "hi" 

By removing the var operator from the example, the message variable becomes global.

After the function test() is called, the variable is defined and becomes accessible outside of the function.

Strict mode throws a ReferenceError when an undeclared variable is assigned a value.

To define more than one variable, use a single statement, separating each variable and optional initialization with a comma:

var message = "hi",  
    found = false, 
    age = 29; 

Here, three variables are defined and initialized.

In strict mode, we cannot define variables named eval or arguments.




PreviousNext

Related