Computer >> Computer tutorials >  >> Programming >> Javascript

Understanding function scope and context in JavaScript?


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

Scope

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

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

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.