Introduction:
The global object in Javascript contains variables and functions that are accessible from anywhere. These are incorporated into the language or environment by default.
However, other objects in the global scope are either created by the user script or provided by the host application.
The global object is known as the window object in a web browser; however, in Node.js, it is known as global.
GlobalThis has recently been added to the language as a standardized name for a global object that should work in all situations. All major browsers are compatible with it.
Also See, Javascript hasOwnProperty
Getting Started:
Alert Ninjas! The ongoing emergence of new technologies in web development keeps the interest in this subject high. But, before you start on the big tasks, we recommend that you understand the fundamentals. With our JavaScript Course, you may jumpstart your web development career by mastering JS principles. It's now the cheapest it's ever been!
We'll use Windows in this article, presuming we're working in a browser. If your script has to run in multiple settings, you should use globalThis instead.
All of the global object's properties can be accessed directly:
window object in the Browser
Any global functions and variables declared with var (not let/const) can be accessed as properties of the window object.
Access Global Variables
var champ = "ninjas"; champ === window.champ; // Returns: true. |
We can retrieve the value of a Global Variable champ from the window object by utilizing the variable name champ as a property name of the Global Object window.champ.
If a value is so important that you want it to be available globally, write it as a property:
// make constant user information global. window.constUser = { |
Access Global Functions
function welcome() { console.log("Hi, Ninjas"); } window.welcome(); // It is the same as the normal invoking: welcome(); |
In the above example, we constructed a global Function named welcome and used the window object to call it. Try this code on an online JS compiler.
Using global variables, on the other hand, is often discouraged. When a function receives "input" variables and generates a specific "output," the code is more readable, has fewer chances of errors, and is easier to test than when the function uses external or global variables.