Skip to main content

Global object

 

Global object

The global object provides variables and functions that are available anywhere. By default, those that are built into the language or the environment.

In a browser it is named window, for Node.js it is global, for other environments it may have another name.

Recently, globalThis was added to the language, as a standardized name for a global object, that should be supported across all environments. It’s supported in all major browsers.

We’ll use window here, assuming that our environment is a browser. If your script may run in other environments, it’s better to use globalThis instead.

All properties of the global object can be accessed directly:

alert("Hello");
// is the same as
window.alert("Hello");

In a browser, global functions and variables declared with var (not let/const!) become the property of the global object:

var gVar = 5;

alert(window.gVar); // 5 (became a property of the global object)

The same effect have function declarations (statements with function keyword in the main code flow, not function expressions).

Please don’t rely on that! This behavior exists for compatibility reasons. Modern scripts use JavaScript modules where such a thing doesn’t happen.

If we used let instead, such thing wouldn’t happen:

let gLet = 5;

alert(window.gLet); // undefined (doesn't become a property of the global object)

If a value is so important that you’d like to make it available globally, write it directly as a property:

// make current user information global, to let all scripts access it
window.currentUser = {
  name: "John"
};

// somewhere else in code
alert(currentUser.name);  // John

// or, if we have a local variable with the name "currentUser"
// get it from window explicitly (safe!)
alert(window.currentUser.name); // John

That said, using global variables is generally discouraged. There should be as few global variables as possible. The code design where a function gets “input” variables and produces certain “outcome” is clearer, less prone to errors and easier to test than if it uses outer or global variables.

Using for polyfills

We use the global object to test for support of modern language features.

For instance, test if a built-in Promise object exists (it doesn’t in really old browsers):

if (!window.Promise) {
  alert("Your browser is really old!");
}

If there’s none (say, we’re in an old browser), we can create “polyfills”: add functions that are not supported by the environment, but exist in the modern standard.

if (!window.Promise) {
  window.Promise = ... // custom implementation of the modern language feature
}

Summary

  • The global object holds variables that should be available everywhere.

    That includes JavaScript built-ins, such as Array and environment-specific values, such as window.innerHeight – the window height in the browser.

  • The global object has a universal name globalThis.

    …But more often is referred by “old-school” environment-specific names, such as window (browser) and global (Node.js).

  • We should store values in the global object only if they’re truly global for our project. And keep their number at minimum.

  • In-browser, unless we’re using modules, global functions and variables declared with var become a property of the global object.

  • To make our code future-proof and easier to understand, we should access properties of the global object directly, as window.x.

Comments

Popular posts from this blog

How to earn money off playstore

https://static1.freebitco.in/banners/728x90-3.png https://static1.freebitco.in/banners/728x90-3.png Earn How to build and grow your app's revenue streams Implement the right monetization strategy Choose the right monetization model Learn about the monetization options available on Google Play and combine them into a strategy that maximizes your app’s revenue. Sell in-app digital goods with Play billing Enhance the revenue from your free-to-download or ad-funded apps by selling durable or consumable digital goods. Sell subscriptions with Play billing Generate a more regular revenue stream from your app by selling access to content or features using subscriptions. Sell goods and services with Google Pay Simplify and streamline your e-commerce purchase funnel using Google Pay to let users buy with their credit or debit cards. Get paid to show ads with Google AdMob Show users ads from over 1 million Google advertisers, ads that fit right in with your app, using Google AdMo...

It’s the season finale of Nigerian Idol Season 6 this Sunday

  On Sunday, July 11, 2021, the winner of Nigerian Idol season 6 will be announced at a special season finale event live on DStv and GOtv. After weeks of watching the Top 11 contestants sing their hearts out on the live shows to earn the fans' votes, the competition is down to two finalists – Kingdom and Francis – vying for the number one spot! In addition to the finale spectacular, there will be surprise performances and other memorable moments. The winner of Nigerian Idol season 6 will win a recording deal of a six track EP, with music video shoots for three of the songs, and over 50 million Naira worth of prizes which include a N30 million cash prize and a brand new SUV. Other prizes include a BIGI branded refrigerator and one year supply of BIGI soft drinks from Rites Food Limited, an all-expense paid trip to Seychelles and a wide range of TECNO products, a weekend getaway package to Dubai for two from TravelBeta and a DStv Explora fully installed with a 12-month DStv Premium s...

Gram Free Review: How to make money online On Gram free

What is Gram Free? Telegram, one of the fast growing social network industry has unveiled their digital currency which is known as  Gram . The  Gram Free  is  a cryptocurrency based on a Ton blockchain platform developed by Telegram. A feature of  Gram is  the high speed of transactions. Cryptocurrencies implemented early blockchain platform due to the low speed of transactions  are more suitable for investment than for use as a payment tool, GramFree  is  also a ‘Get paid To’ website that rewards users with ‘grams’. On a ‘Get Paid To’, or GPT website, users  are  given currency in exchange for doing simple tasks. Usually, this includes buying stuffs from affiliate retailers, inviting new users into the program and sharing things on social media. Is Gram Free Legit? Yes Gram free is legit, Gram free is owned by the Telegram Company, Making the Gram free website trusted and reliable, you earn without investing a dime, the...