DEV Community

Cover image for Global object in JS
Arun Prakash Pandey
Arun Prakash Pandey

Posted on

Global object in JS

About

Every JavaScript environment has one special object called the global object. It has features like: -

  • setTimeout
  • console
  • Math
  • Date
  • Array
  • JSON
  • parseInt

Conceptually, both the below code blocks are same.

// For Example:
console.log(Math.PI);
console.log(setTimeout);
console.log(Date);
Enter fullscreen mode Exit fullscreen mode

&&

globalObject.Math
globalObject.Date
globalObject.console
Enter fullscreen mode Exit fullscreen mode

History

In the browser, it is called window.

window.Math === Math
// true

window.Date === Date
// true

window.console === console
// true
Enter fullscreen mode Exit fullscreen mode

In a run time environment like Node, it is called global.

global.setTimeout
global.console
global.Buffer
Enter fullscreen mode Exit fullscreen mode

However, in workers, it was called self.
So to make it less annoying,
ES20, introduced globalThis.

  1. For Browsers, javascript globalThis === window // true javascript
  2. For run time environments

    globalThis === global
    // true
    
  3. For web workers

    globalThis === self
    // true
    

Top comments (0)