Javascript - Variable Declaration with var

Introduction

When a variable is declared using var, it is automatically added to the most immediate context available.

In a function, the most immediate one is the function's local context.

In a with statement, the most immediate is the function context.

If a variable is initialized without first being declared, it gets added to the global context automatically:

function add(num1, num2) {
   var sum = num1 + num2;
   return sum;
}

var result = add(10, 20);  //30
console.log(sum); //causes an error since sum is not a valid variable

Here, the function add() defines a local variable named sum that contains the result of an addition operation.

This value is returned as the function value, but the variable sum isn't accessible outside the function.

If the var keyword is omitted from this example, sum becomes accessible after add() has been called, as shown here:

function add(num1, num2) {
   sum = num1 + num2;
   return sum;
}

var result = add(10, 20);  //30
console.log(sum);                //30

Here, the variable sum is initialized to a value without using var.

When add() is called, sum is created in the global context and continues to exist even after the function has completed.

In strict mode, initializing variables without declaration causes an error.

Related Topics