JavaScript Variables

This lesson explain you, How to declare JavaScript variable. JavaScript var statement to declare a variables that are scoped to the nearest function block. Another word we can say function scope variable.

If you don't assign variable's value at declaration time, JavaScript automatically assigns the undefined value.

You can't use variable before the declaration otherwise gives an error.

Syntax

var variable_name = value;

Parameter

  • var: JavaScript reserved keyword.
  • var_name: Name of the variable.
  • value: Optional, Initial value assign at the time of declaration.

Shorthand style, you can declare a one or more variables in single statement separated by comma.

var var1 = val1, var2 = val2, ..., varN = valN;

In Strict Mode JavaScript, without var keyword you can't declare and initialize, give an error ReferenceError.

<script>
    "use strict";   // strict mode specification 
    var a = "A";
    b = "B";        // give an ReferenceError 
</script>

One or more variables declare and initialize

var a = 0, b = 0;

One or more variables assign same values

var a = b = c = "hello";
var a = "hello";
var b = a;
var c = b;

document.writeln("a : " + a);
document.writeln("b : " + b);
document.writeln("c : " + c);

Run it...   »

Variable override: you can re-assignment the value of the variable.

var a = "A";
if (a){
    document.writeln("variable a: " + a);
}

var a ="AA";
document.writeln("reinitializing a: " + a);

Run it...   »

var in functional scope: The following var statement example, quote variable scope within callme() function scope. you can't access quote variable outside of function,

function callme() {
    var quote = "clever Boy";
    console.log("inside: "+ quote);
}

callme();
console.log("outside: "+ quote);

Run it...   »

var in loops: var variable visible in the for() loop block,

function callme() {
    for( var i = 1; i < 5; i++ ) {
        console.log(i);                          // i visible on here
    };
    console.log("Outside for block:", i);        // i still visible
}

callme();

Run it...   »

var in global scope: Using var keyword to define variable globally. Once you define globally, you can access inside anywhere.

var i = 1;
console.log("start----", i);
    
function callme() {
    for( i = 1; i < 5; i++ ) {
        console.log("looping time----",i);    // i visible on here
    };
    console.log("function end----", i);       // i visible 
}  
 
callme();
console.log("end----", i);                    // i visible

Run it...   »

Browser Compatibility

  • Google Chrome
  • Mozilla Firefox
  • Internet Explorer
  • Opera
  • Safari

Note: Here details of browser compatibility with version number may be this is bug and not supported. But recommended to always use latest Web browser.