bhavyasaggi.github.io
Sitemap

JavaScript

Inheritance / Prototype Chain

JavaScript implements inheritance by using objects. Each object has an internal link to another object called its prototype.

That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. By definition, null has no prototype and acts as the final link in this prototype chain.

ES6 introduced class keyword but it is mere syntactic sugar atop prototypal mechanism.

// Prototype chain
function Person(name) {
  this.name = name;
}
Person.prototype.greet = function () {
  return `Hi, ${this.name}`;
};

// Class syntax (syntactic sugar)
class Developer extends Person {
  constructor(name, language) {
    super(name);
    this.language = language;
  }

  code() {
    return `Coding in ${this.language}`;
  }
}

Some additional methods to for setting prototype chain.

Common Pitfalls:

Event Loop

flowchart TD
    CS[Call Stack]
    H[Heap]
    EL[Event Loop]
    MQ["Microtask Queue<br/>(Promises)<br/>Higher Priority"]
    TQ["Task Queue<br/>(setTimeout, etc)<br/>Lower Priority"]

    CS --> EL
    H --> EL
    EL --> MQ
    EL --> TQ

Example:

console.log("Start");

setTimeout(() => console.log("Timeout 1"), 0);
setTimeout(() => console.log("Timeout 2"), 0);

Promise.resolve()
  .then(() => {
    console.log("Promise 1");
    return Promise.resolve();
  })
  .then(() => console.log("Promise 2"));

Promise.resolve().then(() => {
  console.log("Promise 3");
  setTimeout(() => console.log("Timeout 3"), 0);
});

console.log("End");

// Output: Start, End, Promise 1, Promise 3, Promise 2, Timeout 1, Timeout 2, Timeout 3

Common Pitfalls:

Microtask vs Macrotask

// Microtasks (higher priority)
Promise.resolve().then(callback);
queueMicrotask(callback);
MutationObserver(callback);

// Macrotasks (lower priority)
setTimeout(callback, 0);
setInterval(callback, delay);
setImmediate(callback); // Node.js
requestAnimationFrame(callback); // Browser
// DOM events

Common Patterns

Additional Patterns

Bundling Modules

In the beginning, Javascript was written as single file with no export/import/require mechanism and closure based abstraction.

const Module = (function () {
  let private = 0;
  return {
    increment: () => ++private,
    getCount: () => private,
  };
})();

Eventually modularity was introduced to organize and structure the code better. Some of which are:

Popular Build tools: Webpack, Vite, Rollup, Parcel

Bundle Performance

Essential Links