Global Object in JavaScript

In JavaScript, the Global Object is an object that always exists in the global scope. All global variables and functions become properties and methods of the Global Object.

In a web browser, the Window object serves as the Global Object. On the server-side environment like Node.js, the Global Object is a built-in object global.

Here are examples of how it works:

  1. Accessing Global Object in a Browser Environment:

In a browser, the Global Object is the Window object. So, if you create a global variable, it becomes a property of the Window object.

1
2
var greeting = "Hello, world!";
console.log(window.greeting); // Outputs: "Hello, world!"
  1. Accessing Global Object in a Node.js Environment:

In Node.js, the Global Object is a built-in object named ‘global’. So, global variables are properties of this global object.

1
2
global.greeting = "Hello, world!";
console.log(greeting); // Outputs: "Hello, world!"
  1. Built-in Constructors and Functions:

JavaScript’s built-in constructors and functions are part of the Global Object, such as:

  • Constructors like Array(), Date(), etc.
  • Functions like isNaN(), parseInt(), etc.
1
2
var arr = new Array(1, 2, 3); // Using the Array constructor
var num = parseInt("123"); // Using the parseInt function
  1. Global Object’s Properties:

Global object has many properties, including:

  • undefined: Represents the undefined value.
  • NaN: Represents “Not-a-Number” value.
  • Infinity: Represents infinity.
1
console.log(Infinity + 1); // Outputs: Infinity
  1. Predefined Core JavaScript Objects:

Predefined core JavaScript objects are also part of the Global Object. They include objects like Math, JSON, and others.

1
2
var pi = Math.PI;
console.log(pi); // Outputs: 3.141592653589793

Overall, the Global Object is essential for providing JavaScript’s basic functionality and serves as the global scope for code execution.