Javascript - var function scope

Introduction

Variables declared using the keyword var are function scoped, meaning their scope was within the function enclosing them.

To create a new block with its own scope, you have to wrap your desired code inside a regular function or an immediately invoked function expression.

For example:

Demo

var price = 10; // Global Declaration 

function showPrice() { 
   var price = 12; // Local Declaration using var 
   console.log(price); // 12 
} 
showPrice();        /*from   w ww .j  av a 2  s. co m*/
console.log(price); // 10

Result

Following is an example of function level scopes with IIFE(immediately invoked function expression):

Demo

var price = 10; // Global Declaration 
(function () { //from w w  w.j av  a  2 s .  c  o m
     var price = 12; // Local Declaration using var 
     console.log(price); // 12 
})(); 
console.log(price); // 10

Result

Here, the variable price is now scoped to the enclosing function and the changes are not leaked to the parent scope, in this case global scope.

The new value price = 12 is only available inside the enclosing function scope.

If we replace the function scope with a block scope:

var price = 10; 
if (price) { 
        price = 12; 
        console.log(price); // 12 
} 
console.log(price); // 12 

Here, the changes inside the if block are leaked to the parent scope.

It tells us that the var declarations are bound to the function scope and does not create block scopes.

With ES6, we now have two additional ways for declaring variables, let and const, both of which declare variables that are block scoped.

Related Topic