What is the global object in Javascript? How does it work?





The global object is very important in Javascript. It contains certain properties that are widely used – remember that in Javascript, the members of an object are typically referred to as “properties”. These properties include certain functions and even other objects, and are all available to any given Javascript program.

When is the global object created?


The global object is created as soon as the Javascript interpreter starts. For Javascript running inside a browser, this means that as soon as a new page is loaded by the browser, the global object will be created.

What is inside the global object?

When the global object is created, it is given some initial properties. These properties include:

global functions such as parseFloat(), and eval()
global properties such as NaN and Inifinity
global objects such as Intl and Math

What is top-level Javascript code?


Top-level Javascript code is Javascript code that is not part of a function – in other words any Javascript code that is outside of a function is considered to be top level code.

You can actually reference the global object in top-level Javascript code. In order to do that, you would use the Javascript keyword this. Here is what it would look like:

//the code below uses an arbitrary variable name - globalObj -
//to reference the global object
var globalObj = this; 

Is the Window object a global object also?

If you have ever dealt with client side Javascript – and by client side Javascript we just mean Javascript used by a web browser – then you have probably heard of the Window object. The Window object also acts as a global object for any and all of the Javascript code within a browser window. Remember that the Window object is basically a representation of an individual browser window.

The Window object can actually be used instead of the this object to reference the global object. This is because the Window object not only has the core global properties, but it also has many other globals that have to do with web browsers and client-side Javascript.

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.

  • Jun Kun

    A well done concise primer to a core topic. I’m learning Javascript at present in my bid to become a full stack web developer and this post has been helpful. Thanks, and keep up the great work!