Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

JavaScript globalThis Object

Nowadays, JavaScript is used in different environments. Apart from the web browsers, which is the most common type of host environment for JavaScript, we can also run our JavaScript programs in servers, smartphones, robotic hardware, etc.

Each environment consists of its object model and has a different syntax for accessing the global object. As we all know, a global thing in the web browser is a window.

Similarly, each environment has its global object, such as in node.js, the global keyword is used to access the global object, web workers used self as a global object.

The different ways of referencing global objects in different environments made it quite tricky for the developers to write a JavaScript code that is executable on multiple platforms.

To overcome all these problems, GlobalThis object was introduced with the help of it we can execute the JavaScript code on multiple environments.

With the help of globalThis object, we can execute our code on window or even non-window context without writing additional checks and tests, which we used to do previously.

In most environments, globalThis directly refers to the global object of that environment.

Generally, this object is very useful when we do not know which environment our code will execute or when we want to make our code executable on different environments.

If we want to use this feature in older browsers that do not support globalThis object, then we have to use a polyfill.

Syntax

globalThis.[variable]= data

Example: globalThis Keyword

In this example, we have saved our data globally, and retrieve it with globalThis object.

<!DOCTYPE html>
<html>
<head>
	<title>globalThis object</title>
</head>
<body>
	<script>
		function setGlobalData() {
		globalThis.mydata ='Hello World';
		}
		setGlobalData();
		console.log(globalThis.mydata ); 
	</script>
</body>
</html>

Output

output

Supported Browsers

  • Chrome
  • Edge
  • Firefox
  • Opera
  • Safari

Conclusion

In this module, we have learned about globalThis object, which is introduced in ECMA Script 2020 also known as ES11 or ES2020. The globalThis object is used when creating a cross-platform code which means that code will be executable on different JavaScript environments.