Skip to content

JavaScript global object

  • by

JavaScript comes with a built-in global object. When scripts create global variables using the var keyword in a web browser environment, those variables become members of the global object.

However, in Node.js, this isn’t always the case. The global object’s properties and functions vary depending on the execution context in which the script is running.

It provides a set of predefined properties and functions that are available to all JavaScript code running in a particular context, such as a web browser or Node.js environment.

In a web browser, the global object is the window object. It represents the global scope of a web page and provides access to various properties and functions, such as document, console, setTimeout, and setInterval.

console.log(globalThis === globalThis.globalThis); // true (everywhere)
console.log(window === window.window); // true (in a browser)
console.log(self === self.self); // true (in a browser or a Web Worker)
console.log(frames === frames.frames); // true (in a browser)
console.log(global === global.global); // true (in Node.js)

In JavaScript, the global object always holds a reference to itself. This means that you can access the global object from within itself by using globalThis, window, self, frames, or global, depending on the execution context.

JavaScript global object example

Simple example code defines your own properties and functions on the global object by simply assigning values to it, like so:

<!DOCTYPE html>
<html>
<body>
    <script>
    // defining a global variable
    window.myVar = 'Hello world!';

    // defining a global function
    function myFunc() {
        console.log('Hello, world!');
    }

    // Call the global function from anywhere in the script
    myFunc(); 

    </script>
</body>
</html>

Output:

JavaScript global object

Do comment if you have any doubts or suggestions on this JS object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading