Variables scope in Javascript
Most of the people assume that scope of variable in Javascript is very much similar to other programming languages like Java or C#. But this assumption is wrong. There are a number of points where the behavior is different.
So what are that points?
  • No block level scope (except block-scoped variables)
  • Variables declaration are moved to top and then run (variables are hoisted)
  • Chaining of scopes. Any function defined within another function has a local scope which is linked to the outer function.
(source w3scholls.com)
So let's see how it really looks like.

1. A globally-scoped variable
A variable declared outside a function, becomes global. All scripts and functions on a web page can access it.
var a = 1;

// global scope
function one() {
  console.log(a);  // --> 1
}


2. Local scope
Variables declared within a JavaScript function, become local to the function. They can only be accessed within the function.
var a = 1;

function one(a) {
  console.log(a);}

function two() {
  var a = 3;
  console.log(a); // --> 3
}
var a = 1;

function one() {
  if (true) {
    var a = 4;
  }

  console.log(a); // --> '4', not the global value of '1'
}


3. Automatically global scope
If you assign a value to a variable that has not been declared, it will automatically become a globalvariable.
function myFunction() {
    carName = "Volvo";
    // code here can use carName
}
No var automatically define variable in the global scope.

4. Catch clause-scoped variable
var e = 5;
console.log(e); // --> 5
try {
    throw 6;
} catch (e) {
    console.log(e); // --> 6
}
console.log(e); // --> 5 


5. Variable hoisting
Function and variable declarations are moved to the top of their current scope i.e hoisted automatically by the Javascript interpreter
function foo() {
     alert("Hi")
     var name = "Saurab";
}
is actually interpreted like this:
function foo() {
     var name;
     alert("Hi");
     name = "Saurab";
}
So the variable name declaration is actually hoisted(moved to the top). The assignment portion remains at it its original place as shown in above example.
There can be some confusing cases too where variable with same is hoisted. Lets take example.
var num = 100;
foo();

function foo(){

    // This prints "undefined", because num is also defined locally below.
    console.log(num);

    if (false)
    {
        var num = 123;  
    }
}

It is very good practice to always declare and define your variables rather than depending on Javascript behaviour.This may lead to confusing code in future when the size grows.

×
×