DEV Community

Cover image for Window and this keyword ?
Utkarsh Yadav
Utkarsh Yadav

Posted on • Updated on

Window and this keyword ?

Table of content

  • Shortest program in JavaScript
  • window keyword
  • This keyword
  • Working behind the scenes

What is the shortest program in JavaScript ?

Running an empty file in JavaScript is the shortest program in JavaScript.

Create a JavaScript file with .js extension and compile the file using Dev Tools in the browser and the magic you would see that even though you have not written a piece of code but your JavaScript engine in the browser will create a complete new Global Execution context with all the methods and API available to you by your browser.

Isn't it interesting?.

Window Keyword

This is a functionality provided by JavaScript engine. basically window is the class in which various functions and methods are encapsulated.

These functions and methods can be used anywhere inside our JavaScript program.

This Keyword

This is an another functionality provided by JavaScript engine. At the Global level this points to window keyword and their functionality.

This is how JavaScript runs --> A global Context is created --> window object is created on initialised by the browser --> the this variable points to the window is created and the complete shortest program of JavaScript runs.

Working behind the scenes.

Steps are:

  • Global Space creation: Anything not inside and block scope or a function scope is said to be in or bounded with Global Space.

Window keyword is Global Space.

So, everything outside the function will be under window keyword object or Global State Object.

Let's see an example to understand it better.

var a = 10;  // Global space
function b() {  // Global space
  var x = 10;  // Not in Global space
console.log(window.a);  // Global space
console.log(a); // Global space
console.log(x); // Global space
Enter fullscreen mode Exit fullscreen mode

Points to be noted:

  • Everything that is inside Global Space are accessed inside window object.
  • Everything that is outside Global Space are not accessed inside window object.

Conclusion: This vs window points to the same global space.

This concludes the blog if you like the content please support me:

Read more blogs: utkarshwhocodesblogs

Happy Coding!

Discussion (0)