Understanding function scope and context in JavaScript?

JavascriptWeb DevelopmentFront End Technology

Context and Scope are not same in JavaScript. Calling a function invocation has both scope and context.


The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes. Global Variable has global scope which means it can be defined anywhere in your JavaScript code. A Local Variable will be visible only within a function where it is defined. Function parameters are always local to that function.


Context is shown how a function is called. Let’s see an example −


var ob1 = {
   display: function() {
      return this;
ob1.display() === ob1;

The above returns true when you can a function as a method of an object. We saw “this” context, which is set to the object the method is called on.

Published on 24-Jan-2018 06:43:58