Javascript - Introduction Variables Scope


Using the var operator to define a variable makes it local to the scope in which it was defined.

For example, defining a variable inside of a function using var means that the variable is destroyed as soon as the function exits:

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

The message variable is defined within a function using var.

The function is called test(), which creates the variable and assigns its value.

Immediately after that, the variable is destroyed so the last line in this example causes an error.

It is, however, possible to define a variable globally by simply omitting the var operator as follows:

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

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

As soon as the function test() is called, the variable is defined and becomes accessible outside of the function once it has been executed.

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 with a comma like this:

var message = "from",  
    found = false, 
    age = 12; 

Here, three variables are defined and initialized.

Variable initializations using different data types may be combined into a single statement.