User Name:


User Email:




This information will only be saved for the purposes of communicating with those who have provided this information voluntarily regarding our services.We will never sell your name or email address to anyone.
© 2018 - First Crazy Developer (Abhishek Kumar)
  

crazydeveloper Context vs Scope in JavaScript

Hi friends, today we will discuss and understand the most importand part 'Scope and Context' in JavaScript. Often people confuse when they talk about Scope and Context in JavaScript.
Scope use to the variables and functional access of JavaScript function, but when we talk about Context, it is the properties and method access of a JavaScript function.
When we analyze the Context vs Scope then we find that both are not same. I met lots of developers and noticed many of them confuse with these and be frank they mixed both to each other.

  • Scope:

There are two types of variable which we use in JavaScript:

1.)  Global
2.)  Local

So we can say Scope are two level global & local. When we define any variables outside the function body will live throughout runtime and can be accessed and altered in any scope. Local variables exists within the function body of which they are defined and different scope for every call of function. They are not accessible outside the function body.

More important thing that currently JavaScript don't support block scope. Means like other language when we define any variable with if, switch, for and while loop block statement are not accessible outside the curly block, but in JavaScript that are accessible outside the curly block but within function body.

However this is soon to change with ES6 specification. The let keyword has officially been added to the ES6 specification. It can be used alternatively to the var keyword and supports the declaration of block scope local variables.

Finally we can say Scope is the functionality which make the visibility of variables within function body.

Look the following Code:

var globalVar=77;
var checkScope = function(){
    var firstVar = 1;
    var childScope = function(){
        var secondVar = 2;
        if(secondVar==2){
          var innerVar=7;
          console.log(firstVar, secondVar, innerVar, globalVar); // outputs: 1, 2, 7, 77
        }
        console.log(firstVar, secondVar, innerVar globalVar,); // outputs: 1, 2, 7, 77
    }
    console.log(firstVar, globalVar, secondVar, innerVar); // Error! secondVar and innerVar are not defined
}
checkScope();

In above code we can understand the scope.

  • Context:

Mostly developers give their all attention to Scope but the concept that is most difficult to grasp is Context.Context is related with object & denote with 'this' keyword for properties. When we implement OOP in JavaScript and defined class with properties and method which help to access these with object of class. Means when we create an instance of function with new operator, all context level variables and method access through that instance.

Look the following code:


var sampleClass = {
    id:1001,
    getId: function(){
        var tempId = 777;
        console.log(tempId, this.id); // outputs 777, 1001
    }
}
sampleClass.getId();

When we went through above code we found that how context works in JavaScript. In above code tempId denote Scope level variable and id with getId() represent as Context.
That was simple enough, but things start to get tricky when functions are used within methods. Take the following modification to the example:

var sampleClass = {
    id:1001,
    getId: function(){
        var tempId = 777;
        var scopeFunction = function(){
        console.log(tempId, this.id); // outputs 777, undefined    
        }
        scopeFunction();
    }
}
sampleClass.getId();

In above code we get error beacause scopeFunction doesn't have Context of sampleClass. So understand that Context couldn't access the Scope level variables, so how can we resolve the above problem?


var sampleClass = {
    id:1001,
    getId: function(){
        var tempId = 777;
        this.scopeFunction = function(){
        console.log(tempId, this.id); // outputs 777, 1001    
        }
        scopeFunction();
    }
}
sampleClass.getId();

Now, in above code scopeFunction come under Context umbrella so all Context level variables can access.

var sampleClass = function(){}
sampleClass.prototype = {
    Id:1001,
    getId: function(){
        var tempId = 777;
        this.sampleFunction();
    },
    sampleFunction: function(){
        console.log(tempId, this.Id); // Reference ERROR!!
    }
}
var sampleObj = new sampleClass();
sampleObj.getId();

Now this.Id is part of an instance object, and there can be several, or even hundreds or thousands of object instances. So it becomes impossible or at least unrealistic to try and access the properties via the object name.

What we understood in above code and what is 'this' ?


var sampleObj = {
    testFunction: function(){
        alert(this === sampleObj);    
    }
};

sampleObj.testFunction(); // true

Now in above code all confusion is cleared. 'this' keyword denote the current object and in above code we proved that.

  • Scope Chain


Execution Context there is a Scope Chain coupled with it. The Scope Chain contains the variable object for every execution context in the execution stack. It is used for determining variable access and identifier resolution. For example:

function ParentFunc(){
    FirstChildFunc();
    function FirstChildFunc(){
        SecondChildFunc();
        function SecondChildFunc(){
            ThirdChildFunc();
            function ThirdChildFunc(){
                // do something
            }
        }
    }   
}
ParentFunc();

In above code the Scope Chain would be, from top to bottom: ThirdChildFunc, SecondChildFunc, FirstChildFunc, ParentFunc & Global. When we talk to access the variables  ThirdChildFunc can access all the top level scope variables and this is the Scope Chain relationship.

There is one more important concept 'Closure' which is already discussed in previous blog.
http://firstcrazydeveloper.com/Blogs/BlogView.html/54/closures-in-javascript


crazydeveloper Home Page 11 June 2015

Become a Fan