Global Object in JavaScript

Global Object in JavaScript

Global Object in JavaScript

The Global Object in JavaScript provides built-in properties, methods, and objects that are accessible anywhere in the code.

What is the Global Object?

  • In browsers, the global object is called window.
  • In Node.js, it is called global.
  • In modern JavaScript (ES2020+), globalThis provides a universal way to access the global object in any environment.

Example: Accessing the Global Object

console.log(window); // In browsers console.log(global); // In Node.js console.log(globalThis); // Works in both environments

Built-in Properties of the Global Object

Global Variables are Properties of window

var name = "Alice"; console.log(window.name); // Output: Alice

var declarations are added as properties of the global object, but let and const are not.

let age = 25; console.log(window.age); // Output: undefined

Built-in Functions

The global object provides built-in functions like:

setTimeout and setInterval

setTimeout(() => console.log("Hello after 2 seconds"), 2000); setInterval(() => console.log("Repeating every second"), 1000);

parseInt and parseFloat

console.log(parseInt("100px")); // Output: 100 console.log(parseFloat("3.14")); // Output: 3.14

isNaN (Check if Not a Number)

console.log(isNaN("hello")); // Output: true console.log(isNaN(123)); // Output: false

Built-in Objects

The global object contains useful built-in objects:

Math

console.log(Math.PI); // Output: 3.141592653589793 console.log(Math.random()); // Output: Random number between 0 and 1

JSON (Convert Between Objects and Strings)

const obj = { name: "Alice", age: 25 }; const jsonString = JSON.stringify(obj); console.log(jsonString); // Output: '{"name":"Alice","age":25}' const parsedObj = JSON.parse(jsonString); console.log(parsedObj); // Output: { name: 'Alice', age: 25 }

Date

const now = new Date(); console.log(now.toISOString()); // Output: Current date in ISO format

globalThis - The Universal Global Object

Before globalThis, accessing the global object in different environments was inconsistent:

EnvironmentGlobal Object
Browserwindow
Node.jsglobal
Web Workersself

Now, globalThis works everywhere:

console.log(globalThis);

šŸŽÆ Summary

✔ The Global Object contains built-in functions, objects, and properties.
✔ In browsers, it's window; in Node.js, it's global; use globalThis for a universal approach.
Avoid polluting the global scope by using let and const instead of var.

šŸš€ The global object is powerful but should be used cautiously to avoid conflicts. Let me know if you need more details! 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close