Languages
[Edit]
EN

JavaScript - scope and context differences

0 points
Created by:
chelsea
326

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

Scope

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';
  
    console.log(a);
}

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

Note:

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

Context

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)

Summary

  • 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

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.

❤️💻 🙂

Join