Shortest JavaScript program

Do you know what's the shortest Javascript program?

Yes, An empty file is the shortest js program.

Javascript engine creates Global execution context and sets its memory space even though no code is present.

Whenever a javascript program runs, the JavaScript engine creates a global object ("window" in the case of a browser), global execution context, and "this" variable.

this === window //true 

//"this" points to the window object. Hence it returns true.

What gets stored inside a window object? Anything that is declared in global space is stored in the window object.

HMMM... you might get a question now - What is global space? Any code we write in js that is not inside a function is present in the global space.

Let's check this with an example:

var num = 10;
var str = "hello";

function b() {
  var x = "world";
}

num and str are present in the global object (window) and not the variable x, since x is not present in global space.

To access num or str, we can do the following:

  1. Variables present in the global space can be accessed by the window object - console.log(window.num)

  2. we can just simply write console.log(num)

  3. Since this points to the window object, we can also use console.log(this.num)

Hope you have learned something new just like me! Thank you.

Credits: Akshay Saini