0
0
Javascriptprogramming~5 mins

this in global scope in Javascript

Choose your learning style9 modes available
Introduction

The this keyword helps you access the current context. In the global scope, it points to the main global object, letting you reach global variables or functions easily.

When you want to refer to the global object from anywhere in your code.
When debugging to check what <code>this</code> points to in the global area.
When writing code that depends on the global environment, like setting global properties.
When you want to understand how <code>this</code> behaves outside functions or objects.
Syntax
Javascript
console.log(this);

In browsers, this in global scope points to the window object.

In Node.js, this in the top-level global scope is an empty object, not the global object.

Examples
Prints the global object in the browser (window).
Javascript
console.log(this);
Shows that global variables declared with var become properties of the global object.
Javascript
var a = 10;
console.log(this.a);
In strict mode, this in global scope is undefined.
Javascript
"use strict";
console.log(this);
Sample Program

This program shows what this points to in global scope and inside a function in strict mode.

Javascript
"use strict";

var name = "Global";

function showThis() {
  console.log(this);
}

console.log(this); // global scope
showThis(); // inside function
OutputSuccess
Important Notes

In browsers, this in global scope usually equals window.

Using "use strict"; changes this to undefined in global scope and functions.

Global variables declared with var become properties of the global object, but let and const do not.

Summary

this in global scope points to the global object (like window in browsers).

Strict mode changes this to undefined in global scope.

Understanding this helps you know where your code runs and what it can access.