Whenever you run some JavaScript code, the global object has been created for you as part of the execution context. By using functions and properties on the global object you perform most, if not all, of the most basic operations in Javascript. You can also add objects to the global object, but this should only be done to a very limited degree. This is to avoid clutter and accidentally overwriting existing values there. In short – to avoid making a mess!

Here are some examples of using the global object:

 

Get the value of the “undefined” value property on the global object, which returns the primitive type undefined:

undefined
>>> undefined

 

Call the “Object” function on the global object, which returns a new empty object:

Object()
>>> Object {}

 

Call the “parseInt” function on the global object, which returns a new Number object:

parseInt(4)
>>> 4
typeof parseInt(4)
>>> "number"

 

Call the stringify function on the JSON object which is a property of the global object:

JSON.stringify('hello')
>>> ""hello""

 

As opposed to the JSON object the global object itself is “invisible”. Just by typing something the JavaScript runtime assumes you are trying to access something on the global object. More on this and function scope later.

Advertisements