JavaScript - scope and context differences

0 points
Created by:

In this article, we would like to show you what is the difference between scope and context in JavaScript.


Scope determines the visibility (or accessibility) of variables. It's achieved by the use of functions and curly braces. Variables can be defined either in local or global scope.

Simple example:

// ONLINE-RUNNER:browser;

var a = 123;

function logNumber() {
    var a = 'text';

logNumber();  // text
console.log(a);  // 123


To see more complex examples check the article - What is scope in JavaScript?


Context is related to objects and how a function is invoked. It refers to the object to which a function belongs when you use this keyword.

Simple example:

// ONLINE-RUNNER:browser;

window.text = 'window text';

const objectA = {
	text: 'object-A text',
  	print: function() {
    	console.log(this.text);  // <------- this.text

objectA.print(); // 'object-A text' (this.text refers to the object.text)

var print = objectA.print;
print(); // 'window text' (this.text refers to the global context - window.text)


  • scope is function-based while context is object-based,
  • every function call has both a scope and a context associated with it,
  • context is associated with this keyword - a reference to the object to which the currently executing code belongs.

Related posts

Alternative titles

  1. JavaScript scope vs. context
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂