JavaScript Global Object Explained with Examples

The global object in JavaScript is an always-defined object that provides variables and functions and is available anywhere. In a web browser, the global object is the window object, while it is named global in Node.js. The global object can be accessed using this operator in the global scope.

Properties are:

  • Infinity
  • NaN
  • Undefined

Functions are:

  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • eval()
  • isFinite()
  • isNaN()
  • parseFloat()
  • parseInt()

window object in the browser

The window object is the Global Object in the Browser. Any Global Variables or Functions can be accessed as properties of the window object.

Access Global Functions

        
function message() {
   console.log("Hello");
}

window.message();    // It is the same as the normal invoking: greeting();
        
    

The example above explains how Global Functions are stored as properties in the window object. We created a Global Function called greeting, then invoked it using the window object.

Infinity

Infinity in JavaScript is a value that represents infinity.

To get negative infinity, use the operator: -Infinity.

NaN

The global NaN value is an acronym for Not a Number. It’s returned by operations such as zero divided by zero, invalid parseInt() operations

isNaN()

Returns true if the value passed as parameter evaluates to NaN.

eval()

This is a special function that takes a string that contains JavaScript code and evaluates/runs it.

        
isNaN('x')          //Output : true

isNaN(2)            //Output : false

isNaN(undefined)    //Output : true        
    

Summary

The global object holds variables that should be available everywhere.

The global object has a universal name globalThis.

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

Posted in

Ankit Patel

Leave a Comment

Your email address will not be published.

Scroll to Top