Skip to content

Latest commit

 

History

History
108 lines (74 loc) · 2.48 KB

File metadata and controls

108 lines (74 loc) · 2.48 KB

Shortest JS Program, window & this keyword

Shortest JavaScript Program

Question interviewers ask: "What's the shortest valid JavaScript program?"

Answer: An empty file is the shortest JavaScript program.

Why?

Even if you write nothing, the JavaScript engine still creates a Global Execution Context (GEC).

The GEC automatically creates:

  • Global Object (window in browsers, global in Node.js)
  • this keyword (points to the global object in non-strict mode)

So, an empty JS file still runs and gives you:

console.log(this); // window in browser
console.log(window); // window object in browser

window Object

In browsers, window is the global object.

It represents the browser window and provides:

  • Global variables
  • Browser APIs (DOM, timers, fetch, etc.)

All global variables declared with var become properties of window:

var a = 10;
console.log(window.a); // 10

But let and const do not attach to window:

let b = 20;
console.log(window.b); // undefined

this Keyword

this refers to the execution context's owner — it depends on how a function is called.

Global Scope

  • In non-strict mode: this → global object (window in browsers).
  • In strict mode: this → undefined.
console.log(this); // window (non-strict)
('use strict');
console.log(this); // undefined

Inside a Function

  • Non-strict mode: this → global object.
  • Strict mode: this → undefined.
function test() {
  console.log(this);
}
test(); // window (non-strict), undefined (strict)

Inside an Object Method

this → the object that called the method.

const obj = {
  name: 'JS',
  getName: function () {
    console.log(this.name);
  },
};
obj.getName(); // "JS"

Arrow Functions

Arrow functions do not have their own this.

They inherit this from the enclosing lexical scope.

const obj = {
  name: 'JS',
  arrow: () => {
    console.log(this.name);
  },
};
obj.arrow(); // undefined (inherited from global scope)

Interview Soundbite

"Even the shortest JS program — an empty file — runs because the engine creates a Global Execution Context with a window object and a this keyword. In browsers, window is the global object, and this in the global scope refers to window in non-strict mode. Inside functions or objects, this changes depending on how the function is called, and arrow functions simply inherit this from their lexical scope."