<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
    <channel>
        <title><![CDATA[TaQtiQ]]></title>
        <description><![CDATA[Latest insights.]]></description>
        <link>https://www.taqtiq.tech</link>
        <generator>RSS for Node</generator>
        <lastBuildDate>Fri, 04 Dec 2026 19:07:09 GMT</lastBuildDate>
        <atom:link href="https://www.taqtiq.tech/feed.xml" rel="self" type="application/rss+xml"/>
        <pubDate>Fri, 04 Dec 2026 04:08:52 GMT</pubDate>
        <language><![CDATA[en]]></language>
        <item>
            <title><![CDATA[Getting Good at Coding]]></title>
            <description><![CDATA[Tips on how you can get good at any programming language.]]></description>
            <link>https://www.taqtiq.tech/blog/getting-good-at-coding</link>
            <guid isPermaLink="false">j971efja09waecnven34wema798ke71n</guid>
            <category><![CDATA[tutorials]]></category>
            <category><![CDATA[opinion]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Fri, 04 Dec 2026 04:08:52 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/feff8bfa-2858-405b-9e28-fd4cf1a909a6" length="0" type="audio/mpeg"/>
            <content:encoded>All programming languages contain two things:

- **Abstract concepts (ideas).**
- **Tokens (sensory data)**.

## Abstract concepts:

Here is an example of a common thing that you will see in programming tutorials and documentation:

![Abstract Concept](/api/storage/kg2ab7px7ga0etzhvwr3pj097d8kfmcm)

What [Web Dev Cody](https://www.youtube.com/@WebDevCody) is explaining in the image that I included above, is how some of the internal architecture of the backend service [Convex](https://www.convex.dev/) works. He uses a diagram to describe how two different **ideas**:

- **Mutations**
- **Queries**

relate to users of a Convex integrated platform and Convex itself.

Understanding the **ideas** that exist in the technology that you are learning is **essential**. Without a backbone of understanding in the **concepts** that exist and how they relate to one another, your knowledge will feel incomplete.

You will get the sense that mysterious forces outside of your purview and control are governing how your application behaves. This leads to a persistent, low-level anxiety about hidden or invisible forces interacting with your application. A &quot;ghost in the machine&quot;.

Whatever service you are using will normally explain these concepts in the documentation. There will also typically be tutorials on YouTube explaining them. The quantity of available tutorials depends on how popular the particular technologies you are using are. There&apos;s normally high quality official documentation available, however, that will go through the ideas.

### Identifying ideas

Ideas are typically communicated through long-form sentences in a conversational format.

Here is an example from the Convex documentation:

![Mutations](/api/storage/kg2c326jbf23080bhcdxhf64jh8kekxr)

Ideas also lean heavily on diagrams or visuals to explain. This is because the idea that is being communicated is often challenging to do so with words alone. The idea is based on experiences and visual observations of the world that would have to be *translated* into plain English for the listener to understand.

Sometimes, the best way to communicate information that you have gathered from an experience is to simply give the other person that same experience that you had. Diagrams and visuals are an attempt at giving the viewer the same experience that the creator had.

When trying to understand any given idea, its always good to consider what the words actually mean, in terms of their **literal definition** and also the themes that they bring up in popular culture. Since we are on the topic, lets look at the word &quot;mutation&quot;.

What is a mutation? 

Here is the literal definition of the word from Google:

&gt; A mutation is a change in an organism&apos;s DNA sequence, or more broadly, a basic alteration or change in something&apos;s form or structure.

The underlying concept that is being communicated here is one of **change** or **alteration**. 

**To mutate is to change.**

If we consider mutants in popular culture (e.g., the mutants from the TV show Futurama, &quot;supermutants&quot; in the Fallout franchise, teenage mutant ninja turtles, etc) - they were once *something* but then **changed** into *something else* (most often through exposure to nuclear radiation that scrambled their DNA).

What this tells us is that the idea of &quot;mutation&quot; in our culture means **to change**.

This helps us a lot to understand what mutation is in programming. When we **mutate** data, we are **changing** it.

The same idea is applied in the context of Convex mutations; they allow us to **change** data that exists in our tables.

Let&apos;s pause for a moment to clear up any misconceptions. What I am explaining here is **not a pun**. It&apos;s not a clever play on words or a funny joke. I am identifying a very critical underlying truth about the word &quot;mutate&quot;. That, in our culture, the underlying meaning being communicated through the word &quot;mutate&quot; is one of change or alteration.

I am not bringing up teenage mutant ninja turtles or Fallout supermutants or Futurama mutants for some comic relief in this article. I&apos;m bringing them up because these are outward manifestations of our cultural understanding of the concept of mutation. Pointing to these examples helps us to identify how we as a society think about what mutation is.

If we can understand our shared cultural perspective on the idea of mutation, then we can make some inferences about what mutation might be in the context of programming.

Ideas can differ in their meaning dependant on context. But there is typically some underlying pattern or truth that is common regardless of the context. When Computer Scientists came up with the idea of mutation; they were not pulling it out of the air. They were modelling it on an existing understanding of the world that had been built up long before computers even existed.

To solidify the point, lets look at another example: queries.

What is a query?

Here is the literal definition from Google:

&gt; A query is a question or request for information, or—as a verb—the act of asking a question to check something or get an answer.

The underlying idea being communicated here is that a **query is a question.** Or that a **query is a request for information**.

This same concept is exists in programming. When we query an API, we are requesting information from it. When we send a query to a database, we are sending a request for information.

This idea is then applied to Convex. When we make a Convex query, we are making a request for information from our Convex tables.

So:

- **Convex mutations allow us to change information.**
- **Convex queries allow us to make requests for information.**

### Learning ideas

Your mind can absorb ideas passively. If you are trying to learn a new programming language, then its often a good idea to *passively* listen to tutorials on that content, even if you are not watching *visually*. This allows you to immerse yourself in that content throughout the day. When travelling, running errands, etc - you can listen to coding tutorials through your headphones. Many programming tutorials will spend large amounts of time where the instructor is talking but the screen is static. In this case, there is nothing you are missing out on visually by only listening to the audio.

## Tokens 

Programming languages also contain massive amounts of immediate sensory data that you need to gather if you want to become good at them. Each programming language contains **tokens**. These are the actual individual words and symbols that you will be typing out when coding an application.

![Tokens](/api/storage/kg2am3628ha0r9ekskdstn7tr18kf3n1)

While you might understand concepts like functions, object-oriented programming, conditional statements, asynchronous programming and so on; if you have not memorised the actual tokens and the order they are meant to appear in to actualise these patterns in your code, you will remain ineffective. 

There will also be gaps in your understanding. Each programming language implements concepts like object-oriented programming differently. Knowing the specifics of *how* they are implemented and deployed in your code really requires gathering enough sensory data.

### Identifying tokens

Most official documentation for any given programming language or technology has a heavy focus on the tokens. Sources like [MDN](https://developer.mozilla.org/en-US/) for instance, go into painstaking detail documenting every token in JavaScript with each of their methods and properties. 

![Tokens2](/api/storage/kg2488p53tq3mkdbnh3zxh79n18kf5zz)

Knowing what tokens to type, the order that they go in, when to use a particular token over another and so on, typically comes down to experience with actually using those tokens. The best thing you can do it actually just code in that programming language. Do not copy code. Do not use AI. Just use the official documentation and a code editor. At first it will be tedious but your understanding quickly gets better.

### Conclusion

For lots of people, the bottleneck in their coding ability is that they just haven&apos;t gathered enough information - ideas or sensory data about that programming language. If you want to get better, just identify what your bottleneck is and target it.</content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript: Primitives, Literals and the Special Types]]></title>
            <description><![CDATA[A quick dive into TypeScript's primitives, literals and special types.]]></description>
            <link>https://www.taqtiq.tech/blog/typescript-primitives-literals-and-the-special-types</link>
            <guid isPermaLink="false">j9750rff3nryc3pq9851jc68qs8kd0t3</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[tutorials]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Thu, 03 Dec 2026 02:24:46 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/736c69cc-7906-4daf-ae1b-e8ee1aa79186" length="0" type="audio/mpeg"/>
            <content:encoded>## Primitives

JavaScript has seven runtime primitive types, and TypeScript has corresponding types for each of them:

- [`string`](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#the-primitives-string-number-and-boolean): Textual data, such as `&quot;hello&quot;`, `&apos;hello&apos;` or `&apos;hello ${name}&apos;`.
- [`number`](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#the-primitives-string-number-and-boolean): Floating-point numbers (all numbers in JavaScript are 64-bit IEEE-754 floating-point values), including integers, deminals, `NaN`, and `Infinity`.
- [`bigint`](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#bigint): Whole numbers of arbitrary size, created with `BigInt(...)` or integer literals ending with `n` (such as `9007199254740991n`). A [`bigint`](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#bigint) and a `number` are distinct types and cannot be added or compared directly with `===` without conversion.
- [`boolean`](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#the-primitives-string-number-and-boolean): Logical values `true` and `false`.
- [`symbol`](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#symbol): Unique values created by calling `Symbol()` or `Symbol.for(...)`, often used as unique object property keys.
- [`undefined`](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#null-and-undefined): Represents a variable that has been declared but not assigned a value, or a missing property/return value.
- [`null`](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#null-and-undefined): Represents the intentional absence of any object value.

### [`null`](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#null-and-undefined) and [`undefined`](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#null-and-undefined) in Strict Mode

When [`strictNullChecks`](https://www.typescriptlang.org/tsconfig/#strictNullChecks) is enabled (which is part of `strict: true`), [`null`](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#null-and-undefined) and [`undefined`](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#null-and-undefined) are not automatically included in other types like  [`string`](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#the-primitives-string-number-and-boolean) or [`number`](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#the-primitives-string-number-and-boolean). If a variable can hold a string or [`null`](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#null-and-undefined), you write `string | null`. Without [`strictNullChecks`](https://www.typescriptlang.org/tsconfig/#strictNullChecks) [`null`](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#null-and-undefined) and [`undefined`](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#null-and-undefined) can be assigned to any type, which hides potential runtime errors.

### Lowercase Primitives vs. Uppercase Constructors 
In TypeScript, [`string`](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#the-primitives-string-number-and-boolean), [`number`](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#the-primitives-string-number-and-boolean), [`boolean`](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#the-primitives-string-number-and-boolean), [`symbol`](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#symbol), and [`bigint`](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#bigint) refer to primitive types. `String`, `Number`, `Boolean`, `Symbol`, and `BigInt` refer to the built-in JavaScript constructor/wrapper types, which include boxed object instances. Primitive types are the standard types to use for values.

## Literals 

A **literal type** is a type that represents one specific value rather than an entire set of values:

- **String literals:** `&quot;GET&quot;`, `&quot;admin&quot;`, `&quot;light&quot;`.
- **Number literals:** `0`, `1`, `200`, `-1`.
- **Boolean literals:** `true`, `false`.
- **BigInt literals:** `0n`, `10n`.

On its own, a literal type like `&quot;success&quot;` means that a value can only be that exact string. Literals become especially useful in **union types**, where you restrict a value to a specific set of choices.

**Example:**

```
// language: ts
// title: Union Types
type Theme = &quot;light&quot; | &quot;dark&quot; | &quot;system&quot;;
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
```

### Type widening and `as const`

When you write `let mode = &quot;dark&quot;`, TypeScript widens the inferred type from `&quot;dark&quot;` to `string` because `mode` can be reassigned to another string later.

When you write `const mode = &quot;dark&quot;`, `mode` cannot be reassigned, so TypeScript infers the literal type `&quot;dark&quot;`.

For objects and arrays, `const` prevents reassigning the variable itself, but its properties or elements can still be mutated and widened. Adding `as const` tells TypeScript to treat the expression as deeply `readOnly` and keep literal types instead of widening them:

```
// language: ts
const config = {
  env: &quot;production&quot;,
  retries: 3,
} as const;
// config.env has type &quot;production&quot;, not string
// config.retries has type 3, not number
```

### Template literal types

Template literal types build new string literal types from existing string literal types, unions, or primitives using backtick syntax.

**Example:**

```
// language: ts
type Size = &quot;sm&quot; | &quot;md&quot; | &quot;lg&quot;;
type PaddingClass = `p-${Size}`;
// Equivalent to: &quot;p-sm&quot; | &quot;p-md&quot; | &quot;p-lg&quot;
```

## Top types: [`any`](https://www.typescriptlang.org/docs/handbook/basic-types.html#any) and [`unknown`](https://www.typescriptlang.org/docs/handbook/basic-types.html#unknown)

In type theory, a **top type** is the supertype of all types - meaning every type can be assigned to it. TypeScript has two top types: [`any`](https://www.typescriptlang.org/docs/handbook/basic-types.html#any) and [`unknown`](https://www.typescriptlang.org/docs/handbook/basic-types.html#unknown).

### [`any`](https://www.typescriptlang.org/docs/handbook/basic-types.html#any)

[`any`](https://www.typescriptlang.org/docs/handbook/basic-types.html#any) disables type checking for the value that it is attached to. Any type can be assigned to [`any`](https://www.typescriptlang.org/docs/handbook/basic-types.html#any), and [`any`](https://www.typescriptlang.org/docs/handbook/basic-types.html#any) can be assigned to almost any type (except [`never`](https://www.typescriptlang.org/docs/handbook/basic-types.html#never)). When you access properties, call methods, or pass any [`any`](https://www.typescriptlang.org/docs/handbook/basic-types.html#any) value into functions, TypeScript does not check whether those operations are valid. If the actual runtime value does not support what you do with it, a runtime error occurs.

**Example:**

```
// language: ts
let value: any = &quot;hello&quot;;
value.toFixed(2); // No compile error, throws TypeError at runtime
```

### [`unknown`](https://www.typescriptlang.org/docs/handbook/basic-types.html#unknown)

[`unknown`](https://www.typescriptlang.org/docs/handbook/basic-types.html#unknown) is the type-safe counterpart to [`any`](https://www.typescriptlang.org/docs/handbook/basic-types.html#any). Like [`any`](https://www.typescriptlang.org/docs/handbook/basic-types.html#any), any value can be assigned to [`unknown`](https://www.typescriptlang.org/docs/handbook/basic-types.html#unknown). Unlike [`any`](https://www.typescriptlang.org/docs/handbook/basic-types.html#any), you cannot directly do anything with an [`unknown`](https://www.typescriptlang.org/docs/handbook/basic-types.html#unknown) value - you cannot access properties on it, call it as a function, or assign it to a more specific type without first narrowing it or validating it.

**Example:**

```
// language: ts
let input: unknown = getExternalInput();

// input.toUpperCase(); // Error: &apos;input&apos; is of type &apos;unknown&apos;

if (typeof input === &quot;string&quot;) {
  console.log(input.toUpperCase()); // Allowed: narrowed to string
}
```

### Choosing [`unknown`](https://www.typescriptlang.org/docs/handbook/basic-types.html#unknown) or  [`never`](https://www.typescriptlang.org/docs/handbook/basic-types.html#never) instead of [`any`](https://www.typescriptlang.org/docs/handbook/basic-types.html#any)

- Use [`unknown`](https://www.typescriptlang.org/docs/handbook/basic-types.html#unknown) when you have a value whose type is not known yet at compile time - such as parsed JSON, a caught error in `catch (error)`, or data from an external API - and you want the compiler to force you to check or validate it before using it.
- Use [`never`](https://www.typescriptlang.org/docs/handbook/basic-types.html#never) (not [`any`](https://www.typescriptlang.org/docs/handbook/basic-types.html#any)) when a type or code path represents something impossible or a function that never returns - not to hold an arbitrary runtime value.

## Bottom type: [`never`](https://www.typescriptlang.org/docs/handbook/basic-types.html#never)

In type theory, a **bottom type** is a subtype of every type and represent the **empty set** - a type that can never have any runtime value. TypeScript&apos;s bottom type is [`never`](https://www.typescriptlang.org/docs/handbook/basic-types.html#never).
- [`never`](https://www.typescriptlang.org/docs/handbook/basic-types.html#never) is assignable to every type.
- No type (not even `string`, `number`, `any` or `unknown`) is assignable to [`never`](https://www.typescriptlang.org/docs/handbook/basic-types.html#never).

[`never`](https://www.typescriptlang.org/docs/handbook/basic-types.html#never) shows up in several key situations:

1. **Functions that never return:** A function that always throws an exception or enters an infinite loop never completes normally, so its return type is `never`.

**Example:**

```
// language: ts
function throwError(message: string): never {
  throw new Error(message);
}
```

2. **Exhaustiveness checking:** When narrowing a union type (such as a discriminated union) in a `switch` or `if/else` chain, handling every member leaves [`never`](https://www.typescriptlang.org/docs/handbook/basic-types.html#never) in the remaining branch. If you pass that remaining value to a helper expecting [`never`](https://www.typescriptlang.org/docs/handbook/basic-types.html#never), TypeScript will report a compile error if a new member is later added to the union and not handled.

**Example:**

```
// language: ts
type Shape =
  | { kind: &quot;circle&quot;; radius: number }
  | { kind: &quot;square&quot;; side: number };

function exhaustiveCheck(x: never): never {
  throw new Error(`Unexpected value: ${x}`);
}

function getArea(shape: Shape): number {
  switch (shape.kind) {
    case &quot;circle&quot;:
      return Math.PI * shape.radius * shape.radius;
    case &quot;square&quot;:
      return shape.side * shape.side;
    default:
      return exhaustiveCheck(shape);
  }
}
```

3. **Impossible states and type filtering:** TypeScript can narrow a variable to [`never`](https://www.typescriptlang.org/docs/handbook/basic-types.html#never) if conditions contradict each other (for example, checking if a `string` is also a `number`). In conditional types, returning [`never`](https://www.typescriptlang.org/docs/handbook/basic-types.html#never) removes a branch when distributing over a union (which is how utility types like `Exclude&lt;T, U&gt;` filter out types).

### [`void`](https://www.typescriptlang.org/docs/handbook/2/functions.html#void)

[`void`](https://www.typescriptlang.org/docs/handbook/2/functions.html#void) is primarily used as the return type of a function to indicate that the function does not return a meaningful value (or that callers should not rely on a return value).

- A function with a [`void`](https://www.typescriptlang.org/docs/handbook/2/functions.html#void) return type can omit a `return` statement or explicitly `return undefined;`.
- Under [`strictNullChecks`](https://www.typescriptlang.org/tsconfig/#strictNullChecks), [`void`](https://www.typescriptlang.org/docs/handbook/2/functions.html#void) is not the same as `undefined` - you generally cannot assign a [`void`](https://www.typescriptlang.org/docs/handbook/2/functions.html#void) value to a variable typed as `undefined` (though a function returning `undefined` is assignable to a function type returning [`void`](https://www.typescriptlang.org/docs/handbook/2/functions.html#void)).
- A callback type with a [`void`](https://www.typescriptlang.org/docs/handbook/2/functions.html#void) return type, such as `() =&gt; void`, can accept a function that returns another type (for example, `Array.prototype.push` returns a `number`, yet `items.forEach(item =&gt; items.push(item))` is valid because the callback&apos;s return value is simply ignored).</content:encoded>
        </item>
        <item>
            <title><![CDATA[How TypeScript Works: Mental Models and Tsconfig.json]]></title>
            <description><![CDATA[An introduction to some core TypeScript concepts and mental models for how to think about TypeScript.]]></description>
            <link>https://www.taqtiq.tech/blog/how-typescript-works-mental-models-and-tsconfigjson</link>
            <guid isPermaLink="false">j97c2g3b3nzhfj8nkt5z20f0yx8k8n60</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[tutorials]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Tue, 01 Dec 2026 22:16:12 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/7394cf10-765c-476c-8377-aab0ec5f3816" length="0" type="audio/mpeg"/>
            <content:encoded>## Mental models for TypeScript

### Superset of JavaScript
- TypeScript is a [superset](https://www.taqtiq.tech/insights/what-is-a-superset-in-programming) of JavaScript.

![TypeScript is a Superset of JavaScript](/api/storage/kg287y1hz0y402g0rx76e81hsh8k9t4g)

- This essentially means that **TypeScript is JavaScript with *extra stuff.***
- Every valid JavaScript program is also syntactically valid TypeScript.
- TypeScript adds syntax for [types](https://www.taqtiq.tech/insights/understanding-type-systems-in-programming) (annotations, interfaces, type aliases, generics) on top of JavaScript.

### Compile-time vs runtime
- TypeScript performs [static analysis](https://www.taqtiq.tech/insights/what-is-static-analysis) *before* code runs.
- Once code is running in the runtime environment (browser, Node.js, Deno, etc), **TypeScript&apos;s type system is no longer enforcing anything** unless runtime validation (e.g., Zod, Valibot) or runtime checks are explicitly written.

### A good mental model
- A good way to think about TypeScript is as a sophisticated [linter](https://www.jetbrains.com/pages/static-code-analysis-guide/linters/) and [transpiler](https://devopedia.org/transpiler) with deep knowledge of **data flow** and **control**, rather than a runtime execution engine.

### Structural typing (&quot;[duck typing](https://devopedia.org/duck-typing)&quot;) with static guarantees

TypeScript uses **structural** (shape-based) typing rather than **nominal** (name-based) typing for most constructs:

- If two types have compatible shapes (properties and method signatures), TypeScript considers them **assignable to each other**, **regardless of whether they have different names.**
- **Exception:** Classes with `private` or `protected` members have **branding/nominal-like constraints** because those members must originate from the same declaration.
- Distinct `enum` declarations **also behave nominally** in certain contexts.

**Example:**

```
// language: ts
interface Point2D {
  x: number;
  y: number;
}

class Vector {
  constructor(public x: number, public y: number) {}
}

// Valid in TypeScript because Vector has `x: number` and `y: number`
const p: Point2D = new Vector(3, 4);
```
 
### Control flow analysis and narrowing
TypeScript doesn&apos;t just look at static declarations. It tracks how types change along execution branches:

- Type guards ([`typeof`](https://www.typescriptlang.org/docs/handbook/2/typeof-types.html), `instanceof`, `&apos;prop&apos; in obj`, [discriminated unions](https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html)) **narrow** a wide union type down to a specific member inside a branch.
- Assignments can also can also narrow or widen types depending on context and [`strictNullChecks`](https://www.typescriptlang.org/tsconfig/#strictNullChecks).

## The compilation pipeline

Understanding the TypeScript compilation pipeline explains:

- ***Why* errors happen.**
- ***How* emit works.**
- ***Where* build tools fit in.**

1. **Source text &amp;rarr; Scanner (Lexer):** Breaks `.ts` / `.tsx` / `.mts` / `.cts` text into a stream of tokens (keywords, identifiers, operators, literals, punctuation).
2. **Tokens &amp;rarr; Parser:** Builds an [Abstract Syntax Tree (AST)](https://dev.to/balapriya/abstract-syntax-tree-ast-explained-in-plain-english-1h38) representing the syntactic structure of your code (and records syntax errors if grammar is invalid).
3. **AST &amp;rarr; Binder:** Creates **symbols** and links declarations with scopes (e.g., connecting a variable reference to its declaration, merging declarations where allowed, like interfaces or namespaces).
4. **Bound AST &amp;rarr; Type Checker:** Walks AST to infer and verify types, check assignability, resolve generics, evaluate conditional/mapped types, and collect semantic diagnostics (type errors).
5. **Typed AST &amp;rarr; Emitter:** Transforms the AST into output files - typically `.js` (downleveled to your specified `target` JS version), `.d.ts` (declaration files for library consumers) and `.d.ts.map` / `.js.map` (source maps).

### Type-Checking vs Emitting

- By default, `tsc` will **still emit `.js` files even when type errors occur**, unless you pass `--noEmitOnError`.
- Modern bundlers and transpilers (like Babel, SWC, esbuild, or Vite&apos;s transform step) often strip types without running full type-checking for speed - meaning that `tsc --noEmit` (or `tsgo` / editor diagnostics) remains essential in CI.

## Type erasure and runtime reality

**Type erasure** is the process by which TypeScript removes type-level constructs when emitting JavaScript.

### What gets erased

- Type annotations (`const count: number = 5` &amp;rarr; `const count = 5;`).
- `interface` and `type` aliases completely disappear in emitted JavaScript.
- Generic type parameters (`function identity&lt;T&gt;(x: T): T` &amp;rarr; `function identity(x) { return x; }`).
- `as` / satisfies type assertions (checked/used at compile time, erased at runtime).
- Parameter property modifiers (`public`, `private`, `protected`, `readonly` on constructor params are used for type checking/emitting assignments, not kept as runtime type metadata).

### What does *not* get erased (runtime constructs)

- **Enums** (standard numeric/string `enum`s emit a runtime object; `const enum` is inlined/erased depending on flags and isolated modules).
- **Classes** (emitted as JavaScript classes/constructor functions).
- **Namespaces** (if they contain runtime values).

### Common mistakes with type erasure

- **Checking an interface with `instanceof`:** Interfaces don&apos;t exist at runtime, so `value instanceof User` will not work. `instanceof` only works on runtime constructor functions/classes.
- **Assuming generics exist at runtime:** You cannot inspect `T` at runtime to branch logic. If you need runtime behaviour, pass a value/schema/factory function.
- **Unvalidated external data:** Typing an API response as `Promise&lt;User&gt;` tells the compiler to *trust* that shape - it does *not* parse or validate JSON at runtime.

## [`tsconfig.json`](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) and essential [`strict`](typescriptlang.org/tsconfig/strict.html) compiler flags
[`tsconfig.json`](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) defines the root of a TypeScript project, specifies input files, and configures the compiler (`compilerOptions`).

### Enabling [`strict`](typescriptlang.org/tsconfig/strict.html)

Setting `&quot;strict&quot;: true` in [`tsconfig.json`](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) is an **umbrella flag that enables a core set of strict type-checking options** (and makes future strict checks easier to adopt).

| Flag (included in `strict: true`) | What It Enforces | Why It Matters for a Safe Codebase |
| --- | --- | --- |
| [`strictNullChecks`](typescriptlang.org/tsconfig/strictNullChecks.html) | `null` and `undefined` are distinct types, not assignable to every type by default. | Prevents the classic `&quot;Cannot read properties of undefined/null&quot;` runtime crashes by forcing explicit handling or narrowing. |
| [`noImplicitAny`](https://www.typescriptlang.org/tsconfig/#noImplicitAny) | Raises an error when a variable or parameter implicitly resolves to `any` without a type annotation or clear inference. | Stops silent &quot;type holes&quot; where bad data slips through undetected. |
| [`strictFunctionTypes`](typescriptlang.org/tsconfig/strictFunctionTypes.html) | Enforces stricter checking on function parameter types (contravariance for function parameters). | Prevents subtle bugs when assigning callbacks or functions with narrower/broader parameter types. |
| [`strictBindCallApply`](https://www.typescriptlang.org/tsconfig/#strictBindCallApply) | Type-checks arguments passed to `.bind()`, `.call()`, and `.apply()` against the target function&apos;s signature. | Catches mismatched argument types or counts in dynamic invocations. |
| [`strictPropertyInitialization`](typescriptlang.org/tsconfig/strictPropertyInitialization.html) | Ensures class fields declared without an initializer are assigned in the constructor (unless marked `!` or typed to allow `undefined`). | Avoids uninitialized class properties that are `undefined` at runtime. |
| [`strictBuiltinIteratorReturn`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-6.html#strict-builtin-iterator-checks-and---strictbuiltiniteratorreturn) *(added in TS 5.6+)* | Uses `BuiltinIteratorReturn` (`any` when `strict` is false, `undefined` when `strict` is true) for built-in iterator return types. | Keeps generator/iterator return types accurate and safe. |
| [`useUnknownInCatchVariables`](https://www.typescriptlang.org/tsconfig/#useUnknownInCatchVariables) *(added in TS 4.4+)* | Types `catch (err)` variables as `unknown` instead of `any`. | Forces you to narrow or inspect errors safely (e.g., `err instanceof Error`) rather than assuming properties exist. |

## Important flags outside of `strict`

While not in the `strict` umbrella, experienced teams commonly pair `strict: true` with:

1. [`noUncheckedIndexedAccess`](typescriptlang.org/tsconfig/noUncheckedIndexedAccess.html): Adds `| undefined` to index signature / array / record lookups (`arr[0]` becomes `T | undefined`), catching out-of-bounds reads.
2. [`exactOptionalPropertyTypes`](https://www.typescriptlang.org/tsconfig/#exactOptionalPropertyTypes): Distinguishes `{ x?: number }` (can be omitted or `undefined` if explicitly allowed) from `{ x?: number | undefined }`.
3. [`noImplicitOverride`](https://www.typescriptlang.org/tsconfig/#noImplicitOverride): Requires the `override` keyword when overriding a base class method, preventing accidental typos from silently creating new methods.
4. [`isolatedModules`](typescriptlang.org/tsconfig/isolatedModules.html) (or [`erasableSyntaxOnly`](typescriptlang.org/tsconfig/erasableSyntaxOnly.html) in modern TypeScript): Ensures files can be safely transpiled in isolation by single-file bundlers/transpilers and clarifies syntax that relies on type erasure.

</content:encoded>
        </item>
        <item>
            <title><![CDATA[What Annoys Me About Coding Interviews]]></title>
            <description><![CDATA[A quick comment on an issue I faced with Tailwind and how it relates to coding interviews for software developer roles.]]></description>
            <link>https://www.taqtiq.tech/blog/what-annoys-me-about-coding-interviews</link>
            <guid isPermaLink="false">j97d4c1sdym6rp71680jzyqyzn8k9ctr</guid>
            <category><![CDATA[opinion]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Tue, 01 Dec 2026 16:07:28 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/a25b64ce-53f4-41f9-8ff7-f2ab39dfc5d7" length="0" type="audio/mpeg"/>
            <content:encoded>I just spent about 2 hours trying to figure out why this extra space was being added between the profile picture/username section and comment body on comments on articles in my Next.js blog.

![Extra Space on Profile Picture](/api/storage/kg21mmnb1erch4f3ke1225tq3d8k9yhj)

![Extra Space on Profile Picture 2](/api/storage/kg252rdbw47mjb1swye6jp2bf18k89v6)

There was no extra padding, margin or spacing being applied to those elements, or the parent components that they inherit styles from.

I was tearing my hair out over this tiny issue and was at a loss for why it was occurring.

Ultimately I discovered that the problem was that the tailwind [`prose`](https://github.com/tailwindlabs/tailwindcss-typography) class was being applied to the *grandparent component* (where the actual article text content is held) which was being inherited by each comment. 

![Prose](/api/storage/kg29bq1p114tanx2p5j6r0vg818k9vwr)

It was this that was applying the mysterious extra spacing between the username/profile picture section and the comment body.

The solution was to just mark the comment section as `not-prose` (though, a potential better solution would be to reorganise my code structure so that each section is distinct... This might be what I do next).

**What does this have to do with coding interviews?**

What I have gained from this little escapade is a much deeper understanding of how `prose` works than what would normally be gained through simply watching tutorials or completing basic coding problems. 

I&apos;ve had to struggle through a difficult problem, think outside the box and use the resources available to me to fix something on a real production app. At the same time, this type of thing isn&apos;t really being assessed in coding interviews that often seem to reel off technical questions about the particular technologies that are being interviewed for.

So somebody who has done route memorisation on a few technical terms may excel at the interview and be preferred for the role - even when they actually haven&apos;t had to struggle through the problems during real product development.</content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Actually Implement a Feature in Your App]]></title>
            <description><![CDATA[An overview of how to take a feature from idea to implementation, with actionable steps for what to do and a real-world example.]]></description>
            <link>https://www.taqtiq.tech/blog/how-to-actually-implement-a-feature-in-your-app</link>
            <guid isPermaLink="false">j97bh7snt87eceft964cjvy9658k7v6e</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[tutorials]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Mon, 30 Nov 2026 22:30:49 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/d9d73802-302d-4d49-b749-101f42125f67" length="0" type="audio/mpeg"/>
            <content:encoded>Recently, I released a feature on my Next.js website that allows users to purchase courses using a Stripe checkout system. I thought I&apos;d write a piece to actually explain my approach to building a feature like this so that others can get a better idea of what to do in their own apps.

![Course Page](/api/storage/kg244mb0785jv6gpy16ab5cx418k6v4e)

### Forming a user requirement 

The first step is to actually come up with an idea for a feature. When working on a new project, I find that the more time and effort I spend working on the project, the more ideas I tend to have.

This is because, after you&apos;ve spent some time working on the project, your mind is then able to look back on your existing pile of work and use it as data for where to go next. You are able to have intuitions about the work that you have already done and do convergent/divergent thinking on it. Whereas when you have no existing work at the start of a project, it can sometimes feel like trying to draw blood from a stone, trying to get *something* from *nothing*. Or in other words, once you get the ball rolling, it becomes easier.

If you have absolutely no idea of what features to add to your program or are starting with nothing, its a good idea to take a look at what other people have already done and go from there. When building the blog for this website, I spent a lot of time looking at existing sites like [dev.to](https://dev.to/) to get a better idea of what features blogs normally have. You should be doing the same for your product.

When looking at existing products that are popular, chances are they have already implemented lots of solutions that are optimal. The features on and structure of popular websites are normally decades worth of iteration and optimisation so you might as well pinch them. There&apos;s no need to re-invent the wheel. It isn&apos;t stealing. This is just how good ideas become industry standards.

In the case of my course purchasing feature, the desired feature can be summed up succinctly in this sentence: 

- **There needs to be a feature that allows users to purchase courses.**

This is the *idea* I came up with for the feature, but it can also be thought of as a **user requirement** for the website. Coming up with the user requirement is step 2.

### Breaking down the problem

The user requirement can then be broken down into a simple flow chart:

![Stripe Checkout Flow Chart](/api/storage/kg21v2q56w9q8wc2c7a2dasbzh8k73pk)

This is a **high level overview** of what the feature needs to do. It can also be thought of in more simple terms as:

1. **The user buys a course.**
2. **The user then gets the course.**

The feature is a simple exchange of inputs and outputs. Which is the shape of pretty much all features in software. Creating our flow chart is step 3. Normally I do not *physically* create a flow chart in the sense of going into a software program and drawing it out, but I am able to break the problem down into actionable steps in my head. 

Whatever method works for you, you should go with. If drawing the flow chart out and taking some time to break down the problem on paper helps, then you should do that. If you are able to work it out mentally then that is fine too.

### Satisfying the flow chart

The goal is now to add code to your app that *satisfies* the flow chart of your feature. This is step 4. If the code that you add satisfies the flow chart, then it satisfies the user requirement that we stated earlier and our feature will have been implemented. Another way of putting it would be that this is now a true statement:

- **Our website has a feature that allows users to purchase courses.**

At this stage, the objective is simply to satisfy each step of the flow chart. *How* you are satisfying each step *isn&apos;t* important right now. The only thing that matters is that each step of the flow chart *is* being satisfied. 

For each step of the flow chart of your feature, there will be billions of different permutations of *how* that step could be implemented. But right now, we aren&apos;t interested in *how* each step is being satisfied, our focus is just that they *are* being satisfied in *some way*.

This is because our goal is to *implement the feature* (by satisfying the flowchart and thus satisfying the user requirement). Not to get stuck perfecting the implementation to step 1 of our flowchart - while the clock ticks down for the delivery date of that feature.

This is how you actually meet deadlines and don&apos;t overshoot them. The focus simply needs to be on satisfying requirements, not designing perfect solutions for them for the time being.

### Iterating on your solution

Of course, at this stage, while the feature will have been implemented, it will most likely not be the optimal solution. Our goal now should be to:

- **Handle edge cases.**
- **Resolve bottlenecks.**

You can handle edge cases simply by testing your solution against what an average person would expect it to do vs what it does. The analogy that I always come to is of patching up a road. What we discussed in the previous section was us laying out the broad structure of the road to our goal. We now have a clear route laid out but we then need to go back and patch up potholes and defects in the road that we may have made while blazing the trail forward, otherwise somebody might fall in.

Bottlenecks occur when there are unnecessary steps between the user and a desired outcome. Or that there are too many inputs for a desired output. The user has to give a lot to get only little from your program. If your product suffers from too much of this it will fail. The juice will not be worth the squeeze.

#### Excess steps:

![Inefficient vs Efficient Approaches](/api/storage/kg2awtcvmnz74ew25crcc84dbs8k6n6v)

#### Excess inputs:

![Many Inputs for an Output](/api/storage/kg2f8gzeymaz62agay8manevjx8k74vh)

Eliminating these unnecessary steps and reducing the number of inputs for a desired output improves the efficacy of your feature.

Iterating on a feature is an ongoing process. As a system matures it eventually becomes more  robust, functional and effective. The key to ensuring that your system improves is continuous real-world feedback. A variety of different users need to interact with your feature from a variety of different devices. This gives broad feedback that you can then improve the system on. You also need to be using your feature yourself so that you can spot edge cases and bottlenecks on your own.

### Recap
To recap, our steps were:

1. **Define a user requirement.**
2. **Break the problem down into a broad flowchart.**
3. **Implement a solution that satisfies the flowchart.**
4. **Iterate on the solution.**

### How I satisfied each step when making my purchase course feature

We&apos;ve already been over how I met steps 1 and 2. As for step 3 (the implementation), I started by adding a new component - `PurchaseSeriesBar` - to my existing course page.

The existing course page fetches information about a course (title, description, cover image and metrics about the course) and the articles within that particular course from my Convex backend. This information is then displayed in various cards and sidebars.

#### Complete `PurchaseSeriesBar` component

```
// language: ts
// title: PurchaseSeriesBar.tsx
&quot;use client&quot;;

import { useCurrentUser } from &quot;@/app/ConvexClientProvider&quot;;
import { Button } from &quot;@/components/ui/button&quot;;
import { api } from &quot;@/convex/_generated/api&quot;;
import { useAction, useConvexAuth, useQuery } from &quot;convex/react&quot;;
import { FunctionReturnType } from &quot;convex/server&quot;;
import { ArrowRight, Check, Loader2 } from &quot;lucide-react&quot;;
import Link from &quot;next/link&quot;;
import { useRouter } from &quot;next/navigation&quot;;
import { useCallback, useEffect, useState } from &quot;react&quot;;
import { toast } from &quot;sonner&quot;;
import { getCurrencySymbol } from &quot;./LeftSidebarArticleSeries&quot;;
import { SignInDialog } from &quot;@/components/web/SignInDialog&quot;;
import { Id } from &quot;@/convex/_generated/dataModel&quot;;

interface PurchaseSeriesBarProps {
  series: FunctionReturnType&lt;typeof api.series.getSeriesBySlug&gt;;
}

export function PurchaseSeriesBar({ series }: PurchaseSeriesBarProps) {
  const router = useRouter();
  const currentUser = useCurrentUser();

  const { isAuthenticated, isLoading: isAuthLoading } = useConvexAuth();
  const [pendingCheckoutSeriesId, setPendingCheckoutSeriesId] = useState&lt;Id&lt;&quot;series&quot;&gt; | null&gt;(null);

  const createCheckout = useAction(api.stripe.createCourseCheckoutSession);
  const [isCheckoutLoading, setIsCheckoutLoading] = useState(false);
  const [isSignInDialogOpen, setIsSignInDialogOpen] = useState(false);

  const shouldCheckPurchase = Boolean(
    series?._id &amp;&amp; (isAuthenticated || currentUser)
  );

  const purchaseState = useQuery(
    api.purchases.getPurchaseState,
    shouldCheckPurchase &amp;&amp; series?._id ? { seriesId: series._id } : &quot;skip&quot;
  );

  const hasPurchased = Boolean(purchaseState?.hasPurchased);

  const startCheckout = useCallback(
    async (seriesId: Id&lt;&quot;series&quot;&gt;) =&gt; {
      try {
        setIsCheckoutLoading(true);
        const { url } = await createCheckout({ seriesId });
        window.location.href = url;
      } catch (error) {
        console.error(&quot;Checkout error:&quot;, error);
        toast.error(&quot;Unable to start checkout. Please try again.&quot;);
        setIsCheckoutLoading(false);
      }
    },
    [createCheckout]
  );

  useEffect(() =&gt; {
    if (!pendingCheckoutSeriesId || isAuthLoading) return;

    if (isAuthenticated || currentUser) {
      const seriesIdToCheckout = pendingCheckoutSeriesId;
      setPendingCheckoutSeriesId(null);
      void startCheckout(seriesIdToCheckout);
    }
  }, [
    pendingCheckoutSeriesId,
    isAuthLoading,
    isAuthenticated,
    currentUser,
    startCheckout,
  ]);

  if (!series) {
    return null;
  }

  const isOwnSeries = Boolean(
    currentUser?.userId &amp;&amp;
      series.profile?.userId &amp;&amp;
      currentUser.userId === series.profile.userId
  );

  const isFree = !series.price || series.price &lt;= 0;

  if (!isOwnSeries &amp;&amp; isFree) {
    return null;
  }

  const handlePurchase = async () =&gt; {
    if (!series._id || hasPurchased) return;

    if (!currentUser) {
      setIsSignInDialogOpen(true);
      return;
    }

    await startCheckout(series._id);
  };

  return (
    &lt;div className=&quot;fixed bottom-0 h-16 w-full border-t bg-background&quot;&gt;
      &lt;div className=&quot;flex flex-row p-4 items-center&quot;&gt;
        {isOwnSeries ? (
          &lt;Button
            type=&quot;button&quot;
            size=&quot;sm&quot;
            className=&quot;cursor-pointer w-fit text-base p-4 ml-auto&quot;
            asChild
          &gt;
            &lt;Link href={`/create-article-series?id=${series._id}`}&gt;
              Edit Series
            &lt;/Link&gt;
          &lt;/Button&gt;
        ) : (
          &lt;div className=&quot;ml-auto flex items-center gap-3&quot;&gt;
            &lt;span
              className={`text-lg font-semibold tabular-nums transition-colors ${
                hasPurchased ? &quot;text-muted-foreground&quot; : &quot;&quot;
              }`}
            &gt;
              {getCurrencySymbol(series.currency || &quot;&quot;)}
              {series.price}
            &lt;/span&gt;

            &lt;Button
              type=&quot;button&quot;
              size=&quot;sm&quot;
              className=&quot;bg-green-600 text-green-50 transition hover:bg-green-900 hover:text-green-200 cursor-pointer w-fit text-base p-4 disabled:opacity-50 disabled:cursor-not-allowed&quot;
              onClick={handlePurchase}
              disabled={isCheckoutLoading || hasPurchased}
            &gt;
              {hasPurchased ? (
                &lt;&gt;
                  &lt;Check className=&quot;mr-2 h-4 w-4&quot; /&gt;
                  Course Purchased
                &lt;/&gt;
              ) : isCheckoutLoading ? (
                &lt;&gt;
                  &lt;Loader2 className=&quot;mr-2 h-4 w-4 animate-spin&quot; /&gt;
                  Redirecting to checkout...
                &lt;/&gt;
              ) : (
                &lt;&gt;
                  Purchase Course
                  &lt;ArrowRight className=&quot;h-6 w-6 stroke-[2.5]&quot; /&gt;
                &lt;/&gt;
              )}
            &lt;/Button&gt;
          &lt;/div&gt;
        )}
      &lt;/div&gt;
      &lt;SignInDialog
        open={isSignInDialogOpen}
        onOpenChange={setIsSignInDialogOpen}
        onSignInSuccess={() =&gt; {
          setPendingCheckoutSeriesId(series._id);
        }}
      /&gt;
    &lt;/div&gt;
  );
}
```

This component contains the purchase button, which is conditionally rendered based on whether the user has already purchased the course or not. It also contains a loading state that is triggered when a user is being redirected to the stripe checkout flow.

```
// language: ts
// title: Purchase Button
&lt;Button
  type=&quot;button&quot;
  size=&quot;sm&quot;
  className=&quot;bg-green-600 text-green-50 transition hover:bg-green-900 hover:text-green-200 cursor-pointer w-fit text-base p-4 disabled:opacity-50 disabled:cursor-not-allowed&quot;
  onClick={handlePurchase}
  disabled={isCheckoutLoading || hasPurchased}
&gt;
  {hasPurchased ? (
    &lt;&gt;
      &lt;Check className=&quot;mr-2 h-4 w-4&quot; /&gt;
      Course Purchased
    &lt;/&gt;
  ) : isCheckoutLoading ? (
    &lt;&gt;
      &lt;Loader2 className=&quot;mr-2 h-4 w-4 animate-spin&quot; /&gt;
      Redirecting to checkout...
    &lt;/&gt;
  ) : (
    &lt;&gt;
      Purchase Course
      &lt;ArrowRight className=&quot;h-6 w-6 stroke-[2.5]&quot; /&gt;
    &lt;/&gt;
  )}
&lt;/Button&gt;
```

![Purchase Course Button](/api/storage/kg27r2sy5yswcyzjnqppbasvzn8k7r7e)

The `onClick` handler for the button calls the `handlePurchase` function which checks if the user is correctly authenticated and, if so, calls the `startCheckout` function to begin the stripe checkout flow.



#### `startCheckout` function

```
// language: ts
// title: startCheckout
const startCheckout = useCallback(
  async (seriesId: Id&lt;&quot;series&quot;&gt;) =&gt; {
    try {
      setIsCheckoutLoading(true);
      const { url } = await createCheckout({ seriesId });
      window.location.href = url;
    } catch (error) {
      console.error(&quot;Checkout error:&quot;, error);
      toast.error(&quot;Unable to start checkout. Please try again.&quot;);
      setIsCheckoutLoading(false);
    }
  },
  [createCheckout]
);
```

As the name suggests `startCheckout` kicks off our Stripe checkout flow. It does this by awaiting `createCheckout`:

```
// language: ts
// title: createCheckout
const createCheckout = useAction(api.stripe.createCourseCheckoutSession);
```

Which is a hook that lets us trigger Convex [actions](https://docs.convex.dev/functions/actions). The particular action that we are triggering is `createCheckoutSession`. I&apos;ve obscured a few details here to protect some of my business logic but the general pattern is the same:

```
// language: ts
// title: createCheckoutSession
const PLATFORM_FEE_RATE = 0.1;

export const createCheckoutSession = action({
  args: {
    itemId: v.id(&quot;items&quot;),
  },
  handler: async (ctx, args) =&gt; {
    const identity = await ctx.auth.getUserIdentity();
    if (!identity) throw new Error(&quot;You must be logged in to complete a purchase.&quot;);

    const checkoutData = await ctx.runQuery(internal.checkout.getCheckoutDetails, {
      itemId: args.itemId,
      buyerUserId: identity.subject,
    });

    if (!checkoutData) throw new Error(&quot;Item not found.&quot;);
    if (checkoutData.alreadyPurchased) throw new Error(&quot;You already own this item.&quot;);
    if (!checkoutData.sellerStripeAccountId || !checkoutData.chargesEnabled) {
      throw new Error(&quot;The seller is not set up to receive payments yet.&quot;);
    }

    const unitAmountCents = Math.round(checkoutData.price * 100);

    const session = await stripe.checkout.sessions.create({
      mode: &quot;payment&quot;,
      allow_promotion_codes: true,
      line_items: [
        {
          price_data: {
            currency: checkoutData.currency.toLowerCase(),
            product_data: {
              name: checkoutData.title,
              description: checkoutData.description || undefined,
              images: checkoutData.imageUrl ? [checkoutData.imageUrl] : [],
            },
            unit_amount: unitAmountCents,
          },
          quantity: 1,
        },
      ],
      payment_intent_data: {
        application_fee_amount: Math.round(unitAmountCents * PLATFORM_FEE_RATE),
        transfer_data: {
          destination: checkoutData.sellerStripeAccountId,
        },
      },
      metadata: {
        itemId: args.itemId,
        buyerUserId: identity.subject,
        sellerId: checkoutData.sellerId,
      },
      success_url: `${process.env.NEXT_PUBLIC_APP_URL}/checkout/success?item=${checkoutData.slug}`,
      cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}/items/${checkoutData.slug}`,
    });

    if (!session.url) {
      throw new Error(&quot;Failed to create Stripe checkout session.&quot;);
    }

    return { url: session.url };
  },
});
```

In our application, we now get a Stripe checkout flow when the user clicks purchase!

![Stripe Checkout Session](/api/storage/kg28hv8g1y6cgy1twg667jvj9x8k77bb)

In our Stripe dashboard, we are then listening for successful purchase events and trigger a webhook when a user makes a purchase so that a table is updated in Convex to give the user their course. We wont show you this bit though, as we want to keep our business logic private!

As you can see however, our frontend is updated nicely to reflect the users newly purchased course.

![Purchase Button Purchased State](/api/storage/kg2bjx3ngjyspadt948sybjt1d8k648r)

![My Library](/api/storage/kg2fet12fs93hatxbj8p3c0dbh8k6773)

![Course in Library](/api/storage/kg20sgkh9xtwzenyjp8zpsx1x18k6zvk)

#### The flowchart is satisfied

If we go back to our original flowchart, we can see that this implementation does indeed satisfy each step.

![Satisfied Flowchart](/api/storage/kg2bfm775cb1dsd5vw62trjtcd8k7agg)

This means that essentially the feature has been successfully built. Of course, this system relies on existing systems that are already present in the website (the course viewing page, the profiles page, the &quot;My Library&quot; page, Stripe onboarding, etc). Building *those* systems just comes down to the same approach, however:

1. **Come up with the idea for the feature.**
2. **Break it down into broad steps.**
3. **Create a solution that satisfies each step.**
4. **Iterate on the solution.**

The last point is quite important here. Although we have built a feature that technically satisfies the requirement, we need to iterate. This is because at this stage we have not handled edge cases and addressed bottlenecks.

While the solution does *exist* at this point, it is very brittle. Let&apos;s look at some examples of how it can be made more robust.

#### Edge case example

One example of an edge case is that users might try to purchase a course *before* they are logged in. If a user is not logged in, then we can&apos;t add the course to their library as we wont know what user to give it to.

When I first made the checkout system, I did include the rudimentary check in `handlePurchase`:

```
// language: ts
// title: !currentUser
if (!currentUser) {
    return;
}
```

While this *will* prevent users from purchasing a course who aren&apos;t properly authenticated, of course, it provides no feedback to the user about what went wrong and where to go from here.

To handle this properly, I created a new component, `SignInDialog`:

```
// language: ts
// title: SignInDialog
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from &quot;../ui/dialog&quot;;
import { Tabs, TabsContent, TabsList, TabsTrigger } from &quot;../ui/tabs&quot;;
import SignInForm from &quot;./SignInForm&quot;;
import SignUpForm from &quot;./SignUpForm&quot;;

interface SignInDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) =&gt; void;
  onSignInSuccess?: () =&gt; void;
}

export function SignInDialog({ open, onOpenChange, onSignInSuccess }: SignInDialogProps) {
    return (
        &lt;Dialog open={open} onOpenChange={onOpenChange} &gt;
            &lt;DialogContent&gt;
                &lt;DialogHeader&gt;
                    &lt;DialogTitle&gt;Sign In or Sign Up&lt;/DialogTitle&gt;
                    &lt;DialogDescription&gt;
                        Sign in or sign up to continue your purchase.
                    &lt;/DialogDescription&gt;
                &lt;/DialogHeader&gt;
                &lt;Tabs defaultValue=&quot;signin&quot; className=&quot;w-full&quot;&gt;
                    &lt;TabsList className=&quot;w-full grid grid-cols-2&quot;&gt;
                        &lt;TabsTrigger 
                            value=&quot;signup&quot; 
                            className=&quot;data-[state=inactive]:cursor-pointer data-[state=active]:cursor-default&quot;
                        &gt;
                            Sign up
                        &lt;/TabsTrigger&gt;
                        &lt;TabsTrigger 
                            value=&quot;signin&quot; 
                            className=&quot;data-[state=inactive]:cursor-pointer data-[state=active]:cursor-default&quot;
                        &gt;
                            Sign in
                        &lt;/TabsTrigger&gt;
                    &lt;/TabsList&gt;
                    &lt;div className=&quot;flex flex-col justify-start mt-4&quot;&gt;
                        &lt;TabsContent value=&quot;signup&quot;&gt;&lt;SignUpForm onSuccess={async () =&gt; { await fetch(&quot;/api/profile-callback&quot;, { cache: &quot;no-store&quot; }); onOpenChange(false); onSignInSuccess?.(); } } /&gt;&lt;/TabsContent&gt;
                        &lt;TabsContent value=&quot;signin&quot;&gt;&lt;SignInForm onSuccess={ () =&gt; { onOpenChange(false); onSignInSuccess?.(); } }/&gt;&lt;/TabsContent&gt;
                    &lt;/div&gt;
                &lt;/Tabs&gt;
            &lt;/DialogContent&gt;
        &lt;/Dialog&gt;
    )
}
```

This prompts the user to sign in or sign up if they click purchase and aren&apos;t yet authenticated. Effectively handling that edge case.

#### Bottleneck example

When working on the edge case solution I mentioned in the previous section, I had to make a choice about *how* I would actually prompt the user to log in. While my final choice was to settle on the option where I place the sign in/up forms in a shadcn `Dialog` component, there were other options too. 

My first idea was to give the purchase button similar functionality to how I handle unauthenticated users trying to click the `My Feed` option in the blog:

![Unauthenticated Toast](/api/storage/kg2fqa0yk205c16w8vht69tnw18k6pvs)

Which is to say, I use a toast to display an error message and a button to sign in.

While this is fine for a users feed, when purchasing courses I think it causes too much friction. A user would have to see a small &apos;Sign In&apos; button at the bottom of the page which is only visible for a few seconds, click it, which then navigates to a different page entirely, so that they can sign in.

This system is too inefficient. If we consider our previous examples:

- **There are too many unnecessary steps** (clicking an extra button to trigger a sign in flow, navigating to a different page entirely, etc).
- **There are too many unnecessary inputs for the desired output** (too many clicks just to sign in/up before purchasing a course).

The more effort that the user has to put in to purchase the course, the lower the likely hood that they will actually go through with the purchase. They might determine that the juice isn&apos;t worth the squeeze.

Using a sign in/up `Dialog` prevents this, however, as it gets the user signed in/up as quickly as possible without any extra clicks or navigation.

### How the feature evolves going forward

This is still a new feature on the platform. Therefore, it will likely continue to go through iterations and updates in the future to further reduce bottlenecks, cover edge cases and interact with other systems that I will build into the platform. As the feature is deployed live on the platform, the evolution of the feature will be in response to real users actually interacting with it. By working this way, we get real-life feedback about how people are actually using the feature so that our updates are grounded in reality instead of being detached from what users actually want out of it. When building features, you typically don&apos;t want to speculate on what users want out of your platform, but rather respond to objective, measurable data and metrics.

We can measure how long users stay on the page, how many click purchase but then don&apos;t end up actually completing the purchase flow, etc. This gives us great insight into what we can actually do to increase purchases.

### What we didn&apos;t cover

Checkout systems can be and typically are more complex than what was covered here. If you go to any popular e-commerce site, they will have a basket system, transaction history, refunds, customer support, etc. 

These might be good features to implement on my site next, and could be the next stage of evolution for this feature. It&apos;s important to be able to identify individual features though. When you go to an e-commerce site and see that you can buy things, its easy to think that *all* the payment features are a single system built in to the site that would take *ages* for one person to make. In other words, its difficult to distinguish between individual systems that can stand on their own when they are interacting closely with other systems.

### How we use the checkout system we built

We just finished building a course that you can purchase for the low price of £6.99. This course contains 4 articles and about 40 minutes of reading material, going into depth on how to get a job as a software developer. It&apos;s great for juniors trying to get into the industry but also contains lots of helpful advice for anyone at any stage of their career. If you are interested, pick it up and give it a read!

[How to Get a Job as a Software Developer](https://www.taqtiq.tech/emmanuel.learmount/series/how-to-get-a-job-as-a-software-developer)
</content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is Static Analysis?]]></title>
            <description><![CDATA[A brief overview of what static analysis is in programming.]]></description>
            <link>https://www.taqtiq.tech/blog/what-is-static-analysis</link>
            <guid isPermaLink="false">j977c9c2grbkxbfb6f2jqqpcr58k70j5</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[tutorials]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Mon, 30 Nov 2026 00:29:29 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/1d3bc10a-7019-4daa-8f55-49c9835eaed5" length="0" type="audio/mpeg"/>
            <content:encoded>**Static analysis is the examination of code (source code, bytecode or compiled binaries) without executing the program.**

**Static analysis tools check code against a set of rules to identify bugs, security flaws, type mismatches and other issues often while you type or during continuous integration.**

### How it works

Static analysers parse code into a structured representation such as:

- An [Abstract Syntax Tree (AST)](https://dev.to/balapriya/abstract-syntax-tree-ast-explained-in-plain-english-1h38)
- A [Control Flow Graph (CFG)](geeksforgeeks.org/software-engineering/software-engineering-control-flow-graph-cfg/)
- A [Data Flow Graph (DFG)](https://www.sciencedirect.com/topics/computer-science/data-flow-graph)

They then run rule engines or formal checks over those structures:

- **Syntax and style linters:** Detect formatting issues, un-used variables, shadowed names, and anti-patterns (e.g., ESLint, Ruff, Clippy).
- **Type and contract checkers:** Ensure type compatibility, nullability, and invariants before runtime (e.g., TypeScript, mypy, Rust&apos;s borrow checker).
- **Data flow and taint analysis:** Track untrusted inputs from entry points (sources) to sensitive operations (sinks) to find SQL injection, command injection, or buffer overflows (e.g., Semgrep, CodeQL, SonarQube).

### Static Analysis vs. Dynamic Analysis

| Aspect | Static Analysis | Dynamic Analysis |
| :--- | :--- | :--- |
| **Execution** | Does **not** run the code | Runs the code (tests, fuzzing, profilers, runtime monitors) |
| **Speed &amp; timing** | Fast. Runs in the editor or pre-merge CI | Slower. Requires builds, environments, or test inputs |
| **Coverage** | Can inspect unreachable or rare branches | Limited to paths actually exercised at runtime |
| **False positives / negatives** | Can produce false positives on complex paths; misses runtime-only config/state bugs | Fewer false positives on observed paths; misses unexercised code |

### Benefits
- **Early feedback:** Detects issues quickly after writing code, long before anything is put to production.
- **Broad path inspection:** Evaluates code on factors that unit tests might skip.

### Limitations
- Tools can sometimes give **false positives** or **false negatives.**
- This means that teams need to tune their static analysis and suppress noise.</content:encoded>
        </item>
        <item>
            <title><![CDATA[Don't Let Other People Be the Lynchpin in Your Success]]></title>
            <description><![CDATA[Not depending on other people for your own success.]]></description>
            <link>https://www.taqtiq.tech/blog/dont-let-other-people-be-the-lynchpin-in-your-success</link>
            <guid isPermaLink="false">j972ap5ypmqm0c8f8ap23283fd8k463c</guid>
            <category><![CDATA[opinion]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Sun, 29 Nov 2026 19:52:54 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/06b03905-8dde-415a-a69b-4cd517779dd7" length="0" type="audio/mpeg"/>
            <content:encoded>In life, most people overpromise and underdeliver. This is because that while *being* competent requires sustained effort, *convincing* other people that you are competent, despite not being so can still get you what you want. For this reason, heavy reliance on other people often times only leads to disappointment. Especially with people who have not demonstrated that they are worthy of putting your trust into.

When you solve problems by *yourself*, *you* become the determining factor in your success. You also remove ambiguity around *whether* you will be successful or not. You know what you are doing. You don&apos;t know what anyone else is doing.

To possess a will to live is to be selfish. Because it is the assertation that ones own needs triumph over the needs of others. Therefore, focusing on yourself affirms life while focusing on others denies it.

To rely on others is to hand your fate off to the whims of somebody else. Not knowing if the tree will bare fruit when it comes time to harvest.</content:encoded>
        </item>
        <item>
            <title><![CDATA[Don't Put Your Hand in the Blender]]></title>
            <description><![CDATA[Decisive communication during high stakes situations.]]></description>
            <link>https://www.taqtiq.tech/blog/dont-put-your-hand-in-the-blender</link>
            <guid isPermaLink="false">j972q2g2h50exjv9yw2q3wgzxh8k4vvh</guid>
            <category><![CDATA[opinion]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Sun, 29 Nov 2026 16:09:36 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/fb583cf9-a011-48a7-9adf-8ac4cd1c6417" length="0" type="audio/mpeg"/>
            <content:encoded>### Communication

One way of telling somebody not to put their hand in a blender is:

&gt; Don&apos;t put your hand in the blender.

Another way of telling somebody to not put their hand in a blender is:

&gt; Uh, I&apos;m not sure if its the best approach to be putting your hand inside the blender. Maybe you should try something else.

The first approach could be construed by some as being *&quot;rude&quot;*. But often times its best to just communicate **directly** and **decisively** if you actually want to be **understood** and taken **seriously**.

The second approach has the same underlying meaning as the first approach but it injects lots of unnecessary ambiguity into the statement and takes longer to communicate. It risks being misinterpreted by the listener or not arriving on time to prevent the crisis.

In the case of putting ones hand into a blender, the stakes are high enough to where not being understood would have catastrophic consequences. In situations like this, consideration for a persons *feelings* needs to just be abandoned. Because your care for the person *as a whole* supersedes for care for their feelings. 

### We choose what the stakes are

A point of resistance that I will often receive centres around the belief that in average daily interactions the stakes just aren&apos;t that high. So all this form of communication does is to hurt peoples feelings. But the truth is, *we* choose what the stakes are. We choose what we think is acceptable and what we tolerate.

Every decision everyone makes everyday is important and matters in terms of that persons life trajectory. You can choose to lower your standards, and allow a person to achieve less than what they were capable of or you can choose to keep those standards high. It is subjective.

Another point of resistance I sometimes receive is the belief that it doesn&apos;t actually matter if somebody&apos;s hand gets blended. This is exemplified in statements like:

&gt; Peoples hands get blended all the time.

&gt; There&apos;s nothing we could have done to prevent it.

&gt; Its nobody&apos;s fault.

&gt; Oh well... We live and we learn...

&gt; There&apos;s nothing wrong with people who are missing a hand.

If you believe this, then you need to raise your standards about what you consider acceptable. It *is* a bad thing if somebody&apos;s hand gets blended. </content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Type Systems in Programming]]></title>
            <description><![CDATA[A brief overview of what type systems are in programming languages.]]></description>
            <link>https://www.taqtiq.tech/blog/understanding-type-systems-in-programming</link>
            <guid isPermaLink="false">j970fdyspj9vakx15rapyzxyah8k4af7</guid>
            <category><![CDATA[tutorials]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Sun, 29 Nov 2026 05:11:49 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/07f97ed8-bd7c-43d4-bb65-e0cce36d4281" length="0" type="audio/mpeg"/>
            <content:encoded>**A type system is a set of rules in a programming language that assigns a **type** (e.g., an `integer`, `boolean`, `string` or custom object) to expressions, variables, and functions and checks that operations use compatible types.**

Type systems are usually described along two main axes:

1. **Checking time.**
2. **Type enforcement/strength.**

| Dimension | Option A | Option B |
| --- | --- | --- |
| **When types are checked** | **Static typing** (compile time / before running) | **Dynamic typing** (runtime / while executing) | 
| **How strictly types are enforced** | **Strong typing** (fewer implicit coercions) | **Weak typing** (more implicit conversions) |

### Type inference

Many languages also use **type inference** where the data type of an expression is automatically detected without requiring explicit type annotations.

### Benefits of type systems

1. **Early bug detection:**
- Static type checkers catch errors during compile time.
- This creates shorter feedback loops as fixing a type error in a code editor takes seconds compared to reproducing it during runtime.
2. **Safer refactoring and easier maintainance:**
- Whenever you change the shape of data, the type system flags every call site across the codebase that needs to adapt.
- When a codebase becomes large, teams can build complex systems without relying on memory or hoping test coverage catches every broken call site.
3. **Improved tooling and developer ergonomics:**
- Types enable accurate autocomplete, jump-to-definition, inline error red squiggles and automated refactoring.
- Reduced guesswork when working with unfamiliar code.
4. **Improved performance and domain modelling:**
- Knowing exact types helps compilers and runtimes lay out memory compactly, avoid boxing or dynamic dispatch, and generate faster machine code.
- Invalid states become unrepresentable.

### Trade offs
1. **Compile time:**
- Heavy type inference can slow down build and type-check times in very large projects.
2. **Upfront design cost:** 
- Modelling types and satisfying the type checker takes extra thought and can take extra boilerplate.</content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is a Superset in Programming?]]></title>
            <description><![CDATA[Defining what a superset is in programming languages.]]></description>
            <link>https://www.taqtiq.tech/blog/what-is-a-superset-in-programming</link>
            <guid isPermaLink="false">j970thwmvmgscrx1xemf7zewrn8k41v7</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[tutorials]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Sun, 29 Nov 2026 04:13:11 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/55fb5549-2344-4739-ab45-c420a76025ee" length="0" type="audio/mpeg"/>
            <content:encoded>**At its core, a superset is a programming language that contains everything in the base language, plus additional features, syntax or functionality.**

![Supersets and Subsets](/api/storage/kg2dsrak0ftc75jrrh5k5r3cxd8k4mwz)

### Common examples

| Superset | Base Language / Standard | What the Superset Adds |
| :--- | :--- | :--- |
| **TypeScript** | JavaScript | Static type checking, interfaces, enums, and modern tooling before compiling down to JavaScript. |
| **SCSS / Sass** | CSS | Variables, nesting, mixins, and functions that compile into standard CSS. |
| **C++** (historically) | C | Object-oriented features, templates, and the Standard Template Library (though modern C and C++ have diverged in edge cases). |
| **Extended SQL dialects** (e.g., PL/pgSQL, T-SQL) | Standard SQL | Procedural logic (loops, conditionals, variables) and database-specific functions. |

### Supersets, subsets and transpilers

- **Superset:** Base language + **extra features** (e.g., TypeScript extends JavaScript).
- **Subset:** A **restricted portion** of the language - often for safety or simplicity (e.g., a restricted JSON or SQL subset).
- **Transpilers:** Browsers and runtime engines typically **don&apos;t run supersets directly.** Instead they translate (**transpile**) the superset code into the base language first and then run it (such as TypeScript to JavaScript or SCSS to CSS).
</content:encoded>
        </item>
        <item>
            <title><![CDATA[Working More Means Compromising Less]]></title>
            <description><![CDATA[A few tips on the benefits of working more and how to do it in a way that is sustainable long term...]]></description>
            <link>https://www.taqtiq.tech/blog/working-more-means-compromising-less</link>
            <guid isPermaLink="false">j97f5ec4qwk9q83831pa9jrfvh8k3xyk</guid>
            <category><![CDATA[opinion]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Sat, 28 Nov 2026 23:18:37 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/369948f8-b199-456a-92fc-201ff3eb9cc4" length="0" type="audio/mpeg"/>
            <content:encoded>When working on a project, you have to make choices. Any choice that you make is a compromise. This is because you are choosing one thing over another. Sure, you can do both. But the steady passage of time does not stop. So all the time that you spend focused on one thing is time not spent on something else.

I noticed this when working on this blog. Every day I have to make choices about the direction I want the project to go in. I could spend hours perfecting one particular feature but those hours could just as well be spent writing articles. What do I want to have at the end of the day? More articles or a better platform? Ultimately, I *need* both before the project is viable. 

The solution is of course to work more, so that I am not made to choose. Working more means that your project is more agile - as it has the ability to easily respond to changes in the industry that it operates in. Working more means that your project has more space to manoeuvre, more room to make mistakes and come back from them. More room to learn and adapt.

When you work more, you do not have to make as many compromises on the project. You do not need to choose between perfecting a feature and writing an article - you can do both. 

Working more naturally means that the compromise then becomes your *personal life*. You stop compromising on the project but instead start compromising on maintaining relationships, having fun - your subjective experience of life. Sacrificing your subjective experience of life is the choice that you make to not be ordinary.

The key to working more in a way that is sustainable is **context switching**. Context switching means that you are diversifying your tasks enough throughout the day so that your experience is varied. Different tasks give different auditory, visual and tactile experiences so changing what you are doing enough can prevent burnout. The important thing is that every task that you undertake during the day is moving your project forward in a measurable way, even if the nature of the task is different.
</content:encoded>
        </item>
        <item>
            <title><![CDATA[The System of Systems]]></title>
            <description><![CDATA["A system is a group of connected or interacting parts that work together as a whole, or an organized method or set of rules for doing something."]]></description>
            <link>https://www.taqtiq.tech/blog/the-system-of-systems</link>
            <guid isPermaLink="false">j97c8rrad45q07j3gh2ghkxahs8jzbmw</guid>
            <category><![CDATA[opinion]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 22:39:04 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/9fdc0401-26c5-4869-a445-e0e603f9497a" length="0" type="audio/mpeg"/>
            <content:encoded>&gt; A system is a group of connected or interacting parts that work together as a whole, or an organized method or set of rules for doing something.

A system of systems is a system that is comprised of other systems. Which are also in turn comprised of *other* systems. Another way to think about it would be fractal systems or a Russian nesting doll of systems.

![Russian Nesting Doll of Systems](/api/storage/kg28k9gqgxw94vsqkjqn63ej6d8k4m2z)

Many things in our world are systems of systems. For example: an iPhone is a system of systems. The phone itself is a system; it is a group of interacting parts that work together as a whole - it has a camera, a battery, a motherboard, a CPU, and so on. They all work together cohesively to form a complete functional product. Those individual parts are complex systems by themselves as well. A CPU has different registers, a cache, a control unit, etc.

It isn&apos;t limited to technology either. The institutions of a country can be thought of as a system of systems. A country will typically have a government with different branches and departments, a healthcare service, military, law enforcement, etc.

When you build a business, really what you are doing is building systems of systems. When you code an application, you are building systems of systems. The overall goal when system building should be to:

1. **Decrease latency *between* systems.**
2. **Increase the efficacy of *any given* system.**

Doing so will improve the salience of the whole. Connecting the driveshaft in a more effective way to the engine makes a car better. Improving a cars tires make the car better. 

Systems need to be integrated so that information can flow freely without being impeded or slowed down. Not isolated or siloed off which causes bottlenecks. If systems aren&apos;t able to interact and communicate with each other on a low level, then there will be bottlenecks.

For instance, in a company, one possible way of running things would be to have the software development team build an application in isolation and then pass it off to the marketing team  who would in turn formulate the best possible way to market the app. This is of course not optimal. Both teams need to be working in close proximity to each other to create a viable product. Or in other words, both systems (the marking team and software dev team) need to be *integrated*.


</content:encoded>
        </item>
        <item>
            <title><![CDATA[Dealing With Rejection, Staying Resilient and Iterating Until You Get Hired]]></title>
            <description><![CDATA[Some tips on how to handle getting rejected in software developer interviews and ensuring that your work is sustainable long term without triggering burnout.]]></description>
            <link>https://www.taqtiq.tech/blog/dealing-with-rejection-staying-resilient-and-iterating-until-you-get-hired</link>
            <guid isPermaLink="false">j97f36f786k3yew8gbz5v0wrqx8jyw98</guid>
            <category><![CDATA[tutorials]]></category>
            <category><![CDATA[opinion]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 05:40:38 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/b5dd22b1-fc6a-4c5a-9e63-360c6bbae336" length="0" type="image/jpeg"/>
            <content:encoded>&lt;p&gt;Some tips on how to handle getting rejected in software developer interviews and ensuring that your work is sustainable long term without triggering burnout.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;This insight is part of a paid series.&lt;/strong&gt; &lt;a href=&quot;https://www.taqtiq.tech/blog/dealing-with-rejection-staying-resilient-and-iterating-until-you-get-hired&quot;&gt;Read the full post on TaQtiQ →&lt;/a&gt;&lt;/p&gt;</content:encoded>
        </item>
        <item>
            <title><![CDATA[Applied Socionics]]></title>
            <description><![CDATA[An article on using socionics intertype relations and mbti personality theory in practise in the workplace and society.]]></description>
            <link>https://www.taqtiq.tech/blog/applied-socionics</link>
            <guid isPermaLink="false">j974d3hpn2d4w1651b1v73rz058jzwhs</guid>
            <category><![CDATA[opinion]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 04:03:00 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/f7a2ab4a-539c-463f-9783-df3de3d3be33" length="0" type="audio/mpeg"/>
            <content:encoded>## Prerequisites 

Understanding of the **Myers-Briggs Type Indicator**, **cognitive functions** and **socionics inter-type relations.**

## The open secret

Based on my experience of life, I have come to regard the existence of different personality types (or as I call them - **cognitive types**) essentially as a **fact**. I will probably write a different article at some point explaining in detail my reasoning for this, but for now it is beyond the scope of this particular article.

I am starting this article with this because it appears to me that sometimes when I bring up anything related to personality typology - some people will immediately dismiss it as being &quot;unscientific&quot; and therefore having no value beyond something fun to think about. A good portion of the population appears to view personality typology to be essentially the same as astrology or a buzzfeed quiz, which is to say that it might be fun to think about or toy around with, but ultimately, when push comes to shove, we should all admit it to be irrational and we absolutely *should not* base any of our institutions on it.

This is a point that I would strongly push back against, however. 

The existence of different cognitive functions in human beings appears to me to be an **open secret.** Anyone who has been through the education system or workplace in any western country (or non-western country as well, I&apos;m sure) will have encountered enough people to have at some point recognised that different people clearly have fundamentally different cognitive orientations towards life. Also, if they are keenly aware, they will have noticed that different people can be organised into groups (or personality types), based on their specific cognitive attitude.

I call it an open secret because most people seem to understand on some intuitive level that the cognitive functions (Si, Ne, Se, Ni, Te, Fi, Fe, Ti) described in tools like the myers-briggs type indicator and their corresponding personality types do indeed exist. Even if someone has never heard of anything related to personality typology, they still can typically identify with relative ease that people can be separated into *types* or *categories* based on their default cognitive attitude.

Popular culture also seems to have no problem with this. Pretty much all literature, movies and TV shows contain characters that fit into some archetype which ultimately corresponds to a real personality type that has already been identified in tools like myers-briggs type indicator or socionics. This is the reason why services like Personality Database can type even fictional characters.

## I can tell a persons personality type with about 70% accuracy after interacting with them for 10 minutes

Its not hard to spot what a persons MBTI type is. You just pay attention to their mannerisms, speech patterns, what they talk about, what they look like, how they dress and what they&apos;re interested in. I don&apos;t get it right immediately 100% of the time but after spending *more* time with the person it becomes abundantly obvious what type they are. To others this can make me come across as a bit uncanny. There is a sense that in the conversation I actually know more about them than sometimes they even know about themselves. Or maybe at least I know something deep about them they they don&apos;t know about themselves.

## My experiences in the workplace and life

I had an experience in the workplace where I came into a job as a junior software developer. The protocol of the company was to pair me up with a more senior developer so that I could learn from them.

After interacting with this senior developer for only a short amount of time, I could very quickly identify that he was an INFP (Fi, Ne, Si, Te) type. Since my personality type is INTJ (Ni, Te, Fi, Se) in socionics that would make this a relationship of *benefit* where he is the *beneficiary* and I am the *benefactor*. Descriptions of the benefit relation often note that they have an impossible time working together due to the asymmetry in cognitive attitude. This corresponds quite well to my experience in that particular workplace. When working together on code, from my perspective, he would choose one approach to solve a problem that I could immediately tell would not work. At the same time, if I told him it would not work before he went and tried it, he would appear to get upset or would try to resist what I was telling him. Overtime I learnt to just keep my mouth shut and let him go in the direction he chose to even when I disagreed with it because saying otherwise would invite scorn. 

Suffice to say, we didn&apos;t end up getting much work done. This is consistent with my experience of other INFP types too. Whenever it comes to work we cannot seem to get anything done. My mother is also an INFP. Whenever I would be in the house on my own everything would function fine - the bins get taken out, the laundry is done and the dishes are washed and packed away. Nothing to complain about. Whenever she would be in the house on her own, the same would also happen. However, when we have to work on it *together* - nothing ever gets done.

I had a very close friend who was an INFP for about a decade. I remember an experience I had with him where we went to Wales on a camping trip. The trip ended up being an absolute mess. We ran out of food, our phones and power banks ran out of battery, we were completely exhausted after walking for hours up steep terrain. We were camping illegally on private land. 

There was a specific instance where we needed to get to the other side of this long, wide ditch with stagnant water at the bottom, that appeared to have some kind of chemical run off from the farm it was in. I jumped over the ditch and cleared it easily but I knew he would have trouble with it. I told him to go and walk the long way round but he insisted on taking his bag off, throwing it over and then jumping over himself.

He threw his bag and it landed right in the water at the bottom of the ditch and then lost his balance and fell in himself.

The bag contained the tent we were both sleeping in, all our food and electronic devices. The bag was not waterproof. Had I gone on this trip with a different type it probably would not have ended up like this.

The truth is, its nobody&apos;s fault. We just have divergent cognitive attitudes. Nobody can really work with their beneficiaries or benefactors.

## Reorganising workplace structure

It makes me think though. In the example I gave where I was made to work with the senior developer - why was I assigned to work with him at all? An infinitely better way of organising the workplace would have been to pair people up with members of the same socionics quadra. This would ensure that the work was actually being done at a steady pace, to a high quality, and that everyone would have been happy exploring their lower cognitive functions and developing as people at the same time.

Of course, the real reason why socionics/MBTI wasn&apos;t being used was because the company was dominated by sensing types who likely had no idea what socionics/MBTI even was. And if they were told about it I&apos;m sure they would laugh and think its just some unscientific hogwash anyway. This is the type of response I have from them all the time so I don&apos;t even bother trying to explain myself.

## Reorganising societal structure

The fact that socionics intertype relations isn&apos;t being taken seriously in the organisation of society to me is just ridiculous. Britain, along with all other western countries will complain about low productivity and GDP growth, meanwhile, millions of people across the country are every day trying to work with people who are not in their socionics quadra and so have completely different cognitive priorities. 

Metaphorically speaking, one person is asking for a hammer and the other person is passing them a banana. And this is happening billions of times across all workplaces in the country. Why complain about low productivity then?

This really cannot be understated. Socionics describes dual relations as pretty much essential for *survival* which lines up quite accurately to my experience of them. If I don&apos;t put an effort into it, I will often forget that Fi and Se even *exist*. That is to say nothing about the shadow functions (for me - Ne, Ti, Fe, Si) which seem to get almost no activation at all.

It is my suspicion that many people who have deep problems in their lives - people who are homeless, addicted to drugs, etc. Would massively benefit from just interacting with their socionics dual type. When people are deep in their primary cognitive function, life becomes very one sided. Great things can come out of that, but also the world can begin to seem very difficult to understand and deal with. For instance, someone deep in introverted feeling or extraverted feeling just becomes completely irrational. 

From my experience as an Ni dominant, being deep in Ni feels essentially like being a ghost. I am completely estranged from my physical surroundings and constantly zoned out in a kind of meditative state.

Why the government doesn&apos;t mandate that firms pair people up with their duals when they enter a workplace? Why doesn&apos;t the government pair everyone in the country up with their duals in general? Maybe everyone would have to attend a mandatory workshop where your personality type would be identified and you would be assigned to another person with your dual type.

It is something that would have to be figured out politically but I suspect doing so would go a long way to actually fixing many of the challenges that the country faces.</content:encoded>
        </item>
        <item>
            <title><![CDATA[6 Step Action Plan for Getting Employed]]></title>
            <description><![CDATA[This article covers a 6 step action plan for getting employed as a software developer. What you should be doing on a daily basis and your mindset for approaching applications.]]></description>
            <link>https://www.taqtiq.tech/blog/6-step-action-plan-for-getting-employed</link>
            <guid isPermaLink="false">j97czb2bn93n091w52fnp714j58jzepn</guid>
            <category><![CDATA[tutorials]]></category>
            <category><![CDATA[opinion]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 02:00:43 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/3f2a8052-39c8-4796-8de8-2f49b038b78e" length="0" type="image/jpeg"/>
            <content:encoded>&lt;p&gt;This article covers a 6 step action plan for getting employed as a software developer. What you should be doing on a daily basis and your mindset for approaching applications.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;This insight is part of a paid series.&lt;/strong&gt; &lt;a href=&quot;https://www.taqtiq.tech/blog/6-step-action-plan-for-getting-employed&quot;&gt;Read the full post on TaQtiQ →&lt;/a&gt;&lt;/p&gt;</content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Pass Interviews for Software Developer Roles]]></title>
            <description><![CDATA[Guidance on what your approach and strategy should be in software developer interviews, what you should be doing beforehand and what actually happens during the interview.]]></description>
            <link>https://www.taqtiq.tech/blog/how-to-pass-interviews-for-software-developer-roles</link>
            <guid isPermaLink="false">j97860vpqnwx1qfynats59rced8jwmtk</guid>
            <category><![CDATA[opinion]]></category>
            <category><![CDATA[tutorials]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Wed, 25 Nov 2026 00:07:15 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/63f17383-3d80-4351-a6b9-274e2c500cd9" length="0" type="image/jpeg"/>
            <content:encoded>&lt;p&gt;Guidance on what your approach and strategy should be in software developer interviews, what you should be doing beforehand and what actually happens during the interview.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;This insight is part of a paid series.&lt;/strong&gt; &lt;a href=&quot;https://www.taqtiq.tech/blog/how-to-pass-interviews-for-software-developer-roles&quot;&gt;Read the full post on TaQtiQ →&lt;/a&gt;&lt;/p&gt;</content:encoded>
        </item>
        <item>
            <title><![CDATA[Choose the Right Thing to Focus On]]></title>
            <description><![CDATA[Avoid wasting time and not moving forward in your career by choosing the right programming languages, tools and frameworks to learn. ]]></description>
            <link>https://www.taqtiq.tech/blog/choose-the-right-thing-to-focus-on</link>
            <guid isPermaLink="false">j97deq4q23vpca6fn9160wx96s8jpa6n</guid>
            <category><![CDATA[opinion]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Sun, 22 Nov 2026 23:32:22 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/ea0c4e8d-c667-4a00-a667-69cfc62d21d3" length="0" type="image/jpeg"/>
            <content:encoded>&lt;p&gt;Avoid wasting time and not moving forward in your career by choosing the right programming languages, tools and frameworks to learn. &lt;/p&gt;&lt;p&gt;&lt;strong&gt;This insight is part of a paid series.&lt;/strong&gt; &lt;a href=&quot;https://www.taqtiq.tech/blog/choose-the-right-thing-to-focus-on&quot;&gt;Read the full post on TaQtiQ →&lt;/a&gt;&lt;/p&gt;</content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript: the Modern Ecosystem, Tooling and Architecture]]></title>
            <description><![CDATA[An in-depth dive into how JavaScript interacts with the browser engine, manages network state, handles modern client storage, and integrates into professional application architecture.]]></description>
            <link>https://www.taqtiq.tech/blog/javascript-the-modern-ecosystem-tooling-and-architecture</link>
            <guid isPermaLink="false">j974nkbz60z1fnrc0eprgbph5n8j7dn7</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[tutorials]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Sat, 14 Nov 2026 22:59:25 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/152c75d2-18b9-4460-a7e5-92459c331029" length="0" type="audio/mpeg"/>
            <content:encoded>## DOM manipulation, Render Pipeline and Modern Events

### The DOM and CSSOM tree

- **The DOM (Document Object Model):** When a browser receives bytes, it parses them through **tokenisation** and **node creation** to construct a **hierarchical tree of objects** representing the structure and content of the document.  

**Bytes to characters**

![Bytes to Characters](/api/storage/kg2cjrna51ja9svbaet77kbctx8j7xcm)

**Tokenisation**

![Tokeniser](/api/storage/kg2a2xjqwt5vjr8brfaxjbgcv18j76xe)

**Tokens to nodes**

![Tokens to Nodes](/api/storage/kg249ance53jan4myjxthzeatx8j6t0e)

**DOM Tree**

![DOM Tree](/api/storage/kg27cg90q93wgsywd1yajackr58j6086)

- For more information about the DOM, you should read our [What Is the Document Object Model in Web Applications](https://www.taqtiq.tech/insights/what-is-the-document-object-model-in-web-applications) article.

- **The CSSOM (CSS Object Model):** At the **same time** that the DOM is constructed, the browser also parses CSS rules into a similar structure called the **CSSOM**. It defines **how styles cascade and apply to respective elements**, accounting for inherited rules.
- **The render tree intersection:** The browser **combines the DOM and CSSOM** to create the **Render Tree**.

### The Render Tree

- The render tree is a crucial internal structure created by web browsers that **determines *what* content appears on the screen and *how* it is styled.**
- Unlike the DOM (which contains every single HTML element including hidden ones), the render tree **only contains visible nodes.**

**Included:** **Every visible DOM element**, along with its computed styles. Pseudo-elements like [`::before`](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/::before) and [`::after`](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/::after) are also included because they generate visual content.

**Excluded:** Elements that are **completely hidden from view** - such as [`&lt;head&gt;`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/head), elements with `display: none;`, and script/style tags - are left out of the render tree entirely.

Elements with `visibility: hidden` or `opacity: 0` *are* included in the render tree because **they still occupy physical space on the page layout**, even if they aren&apos;t visually drawn.

### Layout and Paint

To actually display the page, the browser goes through four different rendering phases once the render tree has been built:

**1. Style**
- The browser evaluates CSSOM rules against the DOM to compute exact styles for every render tree element.

**2. Layout (or Reflow)**
- The browser traverses the render tree and **calculates the exact geometric coordinates** (size and position) **of each node on the screen.**

**3. Paint**
- Pixels are filled onto the screen, rendering text, colours, images, borders, and shadows.

**4. Composite**
- Painted layers are sent to the GPU and drawn to the screen in the correct layering order.

### Critical Rendering Path

CSS is **render blocking**. To maximise performance, developers extract and inline [&quot;Critical CSS&quot;](https://dev.to/rijultp/what-is-critical-css-and-why-it-matters-for-site-speed-33cf) (styles required for above the fold content) directly into the HTML [`&lt;head&gt;`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/head), allowing the browser to render the initial view without waiting for external spreadsheets to load.

#### Layout Thrashing and Reflows

- This performance bottleneck occurs when JavaScript repeatedly interleaves layout *reads* (e.g., querying [`element.offsetWidth`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth)) and *writes* (e.g., modifying [`element.style.width`](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/width)) in a tight loop.

- This forces the browser to prematurely execute synchronous layout recalculations over and over.

- To mitigate this issue you can batch your reads together and your writes together (or use tools like [`requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame)).

### Relation to modern JavaScript applications

When building modern JavaScript applications (using frameworks like React, Vue or Svelte):

- The framework uses a **virtual DOM** or **reactive dependency graph** to efficiently compute changes in the JavaScript state.
-  When state changes, the framework updates the real DOM.
- Any change to the real DOM triggers the browser to update parts of the **CSSOM**, re-evaluate the **Render Tree** and perform a new **Layout** and **Paint**. Minimising unnecessary updates to keep this pipeline fast is the core goal of frontend performance optimisation. 

### Event architecture 

Events in the browser follow a strict three-phase propagation lifecycle:

1. **Capturing (Trickling) Phase:** The event travels downward from the root ([`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window)) through the ancestors down to the target element.
2. **Target Phase:** The event arrives at the specific target element that triggered it.
3. **Bubbling Phase:** The [event bubbles](https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Scripting/Event_bubbling) upward from the target back up to the root ([`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window)).

### [`stopPropagation()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation) vs [`stopImmediatePropagation()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopImmediatePropagation)

**[`event.stopPropagation()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation)**

- Prevents the event from **continuing its journey up through ancestor elements** (stopping the bubbling phase) or **down through the descendants** (stopping the capturing phase).
- However, other listeners on the *same* current element will still execute.

**[`event.stopImmediatePropagation()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopImmediatePropagation)**

- [`event.stopImmediatePropagation()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopImmediatePropagation) goes a step further by stopping event propagation entirely.
- It also blocks any other event listeners attached to the exact same element from running.

### Event delegation

- When attaching event listeners, instead of binding individual event listeners to dozens or even hundreds of child elements (which consumes unnecessary memory and slows down initialisation), **you should attach a single event listener to a common parent element.**

**Example:**

Imagine we have a list of fruit:

```
// language: js
&lt;ul id=&quot;fruit-list&quot;&gt;
  &lt;li&gt;Apple&lt;/li&gt;
  &lt;li&gt;Banana&lt;/li&gt;
  &lt;li&gt;Cherry&lt;/li&gt;
&lt;/ul&gt;
```

Instead of adding a click listener for every single `&lt;li&gt;`, we can add **one** listener to the parent `&lt;ul&gt;` (`fruit-list`):

```
// language: js
// 1. Select the parent element and listen for clicks
document.getElementById(&apos;fruit-list&apos;).addEventListener(&apos;click&apos;, function(event) {
  
  // 2. Check if the clicked element (event.target) is actually an &lt;li&gt;
  if (event.target.tagName === &apos;LI&apos;) {
    
    // 3. Do something with that specific item
    console.log(&apos;You clicked on:&apos;, event.target.textContent);
    
    // Example: change its color or text when clicked
    event.target.style.color = &apos;red&apos;;
  }
});
```

**Benefits of this method**

1. **Faster initialisation and reduced memory usage:** Each time an event listener is attached to an HTML element, the browser has to allocate a chunk of memory to track it. Reducing the number of event listeners your program uses by delegating them properly leads to faster initialisation of the page and less memory usage (resulting in faster load times).
2. **Improved performance:** Performance isn&apos;t just about initial load time; it&apos;s also about how the browser handles updates over time. With event delegation, the parent element stays put, managing events smoothly without constantly binding and unbinding functions as elements change.
3. **Seamlessly handling dynamic DOM elements:** Event delegation gives the developer more control over dynamic DOM elements. Because the event listener is attached to the parent element (e.g., `fruit-list` in the previous example) - adding a fourth element is easier, because you do not have to manually add an event listener for the extra item as it is the parent that is doing the listening.

### Custom events and synthetic events

JavaScript allows you to build **completely bespoke, application-specific** events rather than solely relying on native browser triggers (like `click` or `input`).

This can be achieved with [`CustomEvent`](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent) and [`dispatchEvent()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent).

**Example usage:**

```
// language: js
// 1. Create a custom event with optional payload data
const userLoggedInEvent = new CustomEvent(&apos;userLoggedIn&apos;, {
  detail: { username: &apos;JaneDoe&apos;, role: &apos;admin&apos; },
  bubbles: true,
  cancelable: true
});

// 2. Listen for the custom event on an element
document.addEventListener(&apos;userLoggedIn&apos;, (e) =&gt; {
  console.log(`Welcome back, ${e.detail.username} (${e.detail.role})!`);
});

// 3. Dispatch the synthetic event programmatically
document.dispatchEvent(userLoggedInEvent);
```

## Advanced Browser APIs and Performance Utilities

### Observer APIs

Observer APIs **provide efficient, asynchronous ways to watch for DOM changes or an element&apos;s relationship with the [viewport](https://medium.com/@ayabadrin667/understanding-viewports-in-web-development-7d3df82e2aa4)**, avoiding the performance penalties of continuous polling or heavy event listeners.

### [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver)

- An [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver) tracks when a target element intersects (enters or leaves) the viewport or a specified ancestor container. It is the modern standard for [lazy-loading](https://developer.mozilla.org/en-US/docs/Web/Performance/Guides/Lazy_loading) images, infinite scrolling, and scroll-triggered animations.

**Example:**

```
// language: js
const observer = new IntersectionObserver((entries, observer) =&gt; {
  entries.forEach(entry =&gt; {
    if (entry.isIntersecting) {
      const img = entry.target;
      img.src = img.dataset.src; // Load the actual image
      img.classList.add(&apos;loaded&apos;);
      observer.unobserve(img); // Stop observing once loaded
    }
  });
}, {
  root: null, // uses the viewport
  threshold: 0.1 // triggers when 10% of the element is visible
});

// Observe lazy images
document.querySelectorAll(&apos;img[data-src]&apos;).forEach(img =&gt; observer.observe(img));
```

[`ResizeObserver`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver)

- A [`ResizeObserver`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver) efficiently monitors changes to an elements dimensions (height and width), replacing costly window [`resize`](https://developer.mozilla.org/en-US/docs/Web/API/Window/resize_event) listeners or manual [`getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) loops.

**Example:**

```
// language: js
const boxElement = document.querySelector(&apos;.resizable-box&apos;);

const resizeObserver = new ResizeObserver(entries =&gt; {
  for (let entry of entries) {
    const { width, height } = entry.contentRect;
    console.log(`Element dimensions updated: ${width}px x ${height}px`);
    
    // Adjust layout or styling based on size
    if (width &lt; 400) {
      boxElement.classList.add(&apos;compact&apos;);
    } else {
      boxElement.classList.remove(&apos;compact&apos;);
    }
  }
});

resizeObserver.observe(boxElement);
```

[`MutationObserver`](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver)

- A [`MutationObserver`](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) watches for changes made to the DOM tree, such as added or removed child nodes, modified attributes or text content updates.]

**Example:**

```
// language: js
const targetNode = document.getElementById(&apos;dom-container&apos;);

const config = { attributes: true, childList: true, subtree: true };

const callback = (mutationsList, observer) =&gt; {
  for(let mutation of mutationsList) {
    if (mutation.type === &apos;childList&apos;) {
      console.log(&apos;A child node has been added or removed.&apos;);
    } else if (mutation.type === &apos;attributes&apos;) {
      console.log(`The ${mutation.attributeName} attribute was modified.`);
    }
  }
};

const mutationObserver = new MutationObserver(callback);
mutationObserver.observe(targetNode, config);
```

### Execution scheduling and smooth animations

Managing *when* code runs is crucial for maintaining a high frame rate on your site and keeping the main thread responsive.

[`requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame) vs [`requestIdleCallback`](https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback)

| Feature | [`requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame) (rAF) | [`requestIdleCallback`](https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback) (rIC) |
| :--- | :--- | :--- |
| **Primary Use Case** | Visual updates, DOM animations, rendering. | Low-priority background tasks, analytics tracking, pre-fetching. |
| **Timing** | Synchronized with the browser&apos;s repaint cycle (before the next frame). | Runs during the browser&apos;s idle periods between frames. |
| **Deadline Awareness** | No explicit deadline; must complete within the frame budget (~16.6ms). | Provides a `deadline` object with `timeRemaining()` to prevent freezing. |

**Example:**

```
// language: js
// requestAnimationFrame: Smooth Animation
let posX = 0;
function step(timestamp) {
  posX += 2;
  document.getElementById(&apos;box&apos;).style.transform = `translateX(${posX}px)`;
  
  if (posX &lt; 300) {
    requestAnimationFrame(step); // Keeps looping for the next frame
  }
}
requestAnimationFrame(step);

// requestIdleCallback: Offloading non-critical work
function processAnalytics(deadline) {
  while (deadline.timeRemaining() &gt; 0 &amp;&amp; queue.length &gt; 0) {
    sendMetric(queue.shift());
  }
  
  if (queue.length &gt; 0) {
    requestIdleCallback(processAnalytics); // Resume next time browser is idle
  }
}
requestIdleCallback(processAnalytics, { timeout: 2000 }); // Guarantees execution within 2s even if not idle
```

### Rate limiting handlers

High-frequency events like [`scroll`](https://developer.mozilla.org/en-US/docs/Web/API/Document/scroll_event), [`resize`](https://developer.mozilla.org/en-US/docs/Web/API/Window/resize_event) and [`input`](https://developer.mozilla.org/en-US/docs/Web/API/Element/input_event) can fire multiple times per second, causing layout thrashing or performance bottlenecks if left unmanaged.

#### Production-grade debounce
- This delays invoking a function until *after* a specified amount of time has elapsed since the last time it was invoked.
- It is ideal for search inputs ([`input`](https://developer.mozilla.org/en-US/docs/Web/API/Element/input_event) events) where you only want to query the API after the user stops typing.

**Example:**

```
// language: js
function debounce(fn, delay) {
  let timeoutId;
  return function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() =&gt; {
      fn.apply(this, args);
    }, delay);
  };
}

// Usage with an input field
const handleSearch = debounce((event) =&gt; {
  console.log(&apos;Fetching search results for:&apos;, event.target.value);
}, 300);

document.getElementById(&apos;search-input&apos;).addEventListener(&apos;input&apos;, handleSearch);
```

#### Production-grade throttle
- This ensures that a function is called at most *once* every specified period, no matter how many times the event fires.
- It is ideal for window [`resize`](https://developer.mozilla.org/en-US/docs/Web/API/Window/resize_event) and [`scroll`](https://developer.mozilla.org/en-US/docs/Web/API/Document/scroll_event) tracking.

**Example:**

```
// language: js
function throttle(fn, limit) {
  let inThrottle;
  return function(...args) {
    if (!inThrottle) {
      fn.apply(this, args);
      inThrottle = true;
      setTimeout(() =&gt; {
        inThrottle = false;
      }, limit);
    }
  };
}

// Usage with window scroll
const handleScroll = throttle(() =&gt; {
  console.log(&apos;Scroll event handled at:&apos;, window.scrollY);
}, 200);

window.addEventListener(&apos;scroll&apos;, handleScroll);
```

## Networking, HTTP and Asynchronous Data Transfer

### The modern [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API

- The JavaScript [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API provides a powerful, flexible and [promise-based](https://www.taqtiq.tech/insights/javascript-mastering-the-event-loop-callbacks-and-asynchronous-code#the-shift-to-using-promises) mechanism for making HTTP requests.
- It relies on three core interfaces:

1. **[`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers) Object**

- Allows you to query, set, append and delete HTTP headers explicitly.

2. **[`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) Object**

- Encapsulates a resource request, including URL, method, headers, body, mode and cache directives.

3. **[`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) Object**

- Represents the HTTP response, providing status information ([`ok`](https://developer.mozilla.org/en-US/docs/Web/API/Response/ok), [`status`](https://developer.mozilla.org/en-US/docs/Web/API/Response/status), [`statusText`](https://developer.mozilla.org/en-US/docs/Web/API/Response/statusText)) and body parsing methods ([`.json()`](https://developer.mozilla.org/en-US/docs/Web/API/Response/json_static), [`.text()`](https://developer.mozilla.org/en-US/docs/Web/API/Response/text), [`.blob()`](https://developer.mozilla.org/en-US/docs/Web/API/Response/blob)).

### Handling HTTP codes

- Unlike older libraries (like [Axios](https://www.geeksforgeeks.org/html/what-is-axios/)), [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) **does not reject** its promise on HTTP error status codes (such as `404 Not Found` or `500 Internal Server Error`).

- It only rejects on network failures or request blocking. Therefore, you must manually check [`response.ok`](https://developer.mozilla.org/en-US/docs/Web/API/Response/ok) (which is `true` for status codes in the `200-299` range).

**Example:**

```
// language:js
async function fetchUserData(userId) {
  // Creating a custom Headers object
  const headers = new Headers({
    &apos;Content-Type&apos;: &apos;application/json&apos;,
    &apos;Authorization&apos;: &apos;Bearer YOUR_TOKEN_HERE&apos;
  });

  // Creating a Request object
  const request = new Request(`https://api.example.com/users/${userId}`, {
    method: &apos;GET&apos;,
    headers: headers,
    cache: &apos;no-cache&apos;
  });

  try {
    const response = await fetch(request);

    // Explicitly check for non-2xx HTTP responses
    if (!response.ok) {
      throw new Error(`HTTP Error! Status: ${response.status} ${response.statusText}`);
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error(&apos;Fetch operation failed:&apos;, error.message);
    throw error;
  }
}
```

### Request interception and cancellation

- When building responsive apps, you will often need to cancel pending network requests - such as when a user types rapidly in a search box or navigates away from a page.
- This is managed with [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) and [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal).

1. [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController)
- A controller object that allows you to abort one or more web requests as needed.

2. [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)
- A signal instance tied to the controller that is passed into the fetch configuration to listen for cancellation events.

**Example:**

```
// language: js
let currentController = null;

async function searchProducts(query) {
  // Cancel any ongoing previous request
  if (currentController) {
    currentController.abort();
  }

  // Create a new controller for the current request
  currentController = new AbortController();
  const { signal } = currentController;

  try {
    const response = await fetch(`https://api.example.com/search?q=${encodeURIComponent(query)}`, {
      signal // Bind the signal to the fetch request
    });

    if (!response.ok) throw new Error(&apos;Search failed&apos;);
    
    const results = await response.json();
    return results;
  } catch (error) {
    if (error.name === &apos;AbortError&apos;) {
      console.log(&apos;Previous request was successfully aborted.&apos;);
    } else {
      console.error(&apos;Fetch error:&apos;, error);
    }
  }
}
```

### Data serialisation formats

- Different data types require different serialisation strategies before transmission across a network.

#### JSON, [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData), and binary data types

1. **JSON:** Used for structured textual data via [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) for payloads and [`response.json()`](https://developer.mozilla.org/en-US/docs/Web/API/Response/json_static) for parsing.
2. [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData): Used to construct key/value pairs representing form fields and binary files, natively handling [`multipart/form-data`](https://medium.com/@muhebollah.diu/understanding-multipart-form-data-the-ultimate-guide-for-beginners-fd039c04553d) encoding.
3. Binary data ([`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob), [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray))
    - **[`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) (Binary Large Object):** Represents immutable raw data, frequently used for files, images, or blobs of downloaded data.
    - **[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer):** A low-level, fixed-length block of raw binary memory data.
    -  [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray): Views (e.g., [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array)) that let you read and write raw binary data stored inside an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer).

**Example:**

```
// language: js
async function handleDataSerialization() {
  // 1. FormData Example (e.g., file uploads)
  const formData = new FormData();
  formData.append(&apos;username&apos;, &apos;jane_doe&apos;);
  formData.append(&apos;avatar&apos;, new Blob([&apos;fake-image-bytes&apos;], { type: &apos;image/png&apos; }), &apos;avatar.png&apos;);

  // 2. Blob &amp; Downloading Binary Data
  const imageResponse = await fetch(&apos;https://example.com/image.png&apos;);
  const imageBlob = await imageResponse.blob(); // Handled as a Blob
  const imageUrl = URL.createObjectURL(imageBlob);

  // 3. ArrayBuffer &amp; TypedArrays (Low-level manipulation)
  const bufferResponse = await fetch(&apos;https://example.com/audio.raw&apos;);
  const arrayBuffer = await bufferResponse.arrayBuffer(); // Get raw buffer
  
  // Create a TypedArray view (e.g., 16-bit unsigned integers)
  const uint16View = new Uint16Array(arrayBuffer);
  console.log(`First audio sample value: ${uint16View[0]}`);
}
```

### Real-time data streams

- Real-time communication enables servers to **push data to clients instantaneously** without requiring repeated polling.

### Server-Sent Events (SSE): Uni-directional streaming via [`EventSource`](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)

- SEE establishes a **uni-directional** connection where the server streams updates down a persistent HTTP connection using the text/event-stream format. 
- It handles automatic reconnection out of the box.

**Example:**

```
// language: js
function setupSSE() {
  const eventSource = new EventSource(&apos;https://api.example.com/notifications-stream&apos;);

  // Listen for default messages (unnamed events)
  eventSource.onmessage = (event) =&gt; {
    const data = JSON.parse(event.data);
    console.log(&apos;Received notification update:&apos;, data);
  };

  // Listen for custom named events from the server
  eventSource.addEventListener(&apos;price-update&apos;, (event) =&gt; {
    const stockData = JSON.parse(event.data);
    console.log(&apos;Stock price changed:&apos;, stockData);
  });

  eventSource.onerror = (error) =&gt; {
    console.error(&apos;SSE connection error occurred:&apos;, error);
    // EventSource automatically attempts to reconnect
  };
}
```

### WebSockets: Full-duplex communication via the [`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) API

- Unlike SEE, WebSockets provide a [**full-duplex**](https://www.techtarget.com/news/full-duplex/861989/) (two-way) real-time communication channel over a single TCP socket, allowing both client and server to send messages independently at any time.

**Example:**

```
// language: js
function setupWebSocket() {
  const socket = new WebSocket(&apos;wss://stream.example.com/socket&apos;);

  socket.onopen = (event) =&gt; {
    console.log(&apos;WebSocket connection established.&apos;);
    // Send a message to the server once open
    socket.send(JSON.stringify({ action: &apos;subscribe&apos;, channel: &apos;ticker&apos; }));
  };

  socket.onmessage = (event) =&gt; {
    const message = JSON.parse(event.data);
    console.log(&apos;Message received from server:&apos;, message);
  };

  socket.onerror = (error) =&gt; {
    console.error(&apos;WebSocket error:&apos;, error);
  };

  socket.onclose = (event) =&gt; {
    console.log(`WebSocket connection closed. Code: ${event.code}, Reason: ${event.reason}`);
  };
}
```

## Client-Side Storage and Data Persistence

### Key-value storage: [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) vs [`sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage)

- [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) and [`sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) are built-in browser Web Storage APIs that allow you to store key-value pairs.
- They operate within a specific origin (domain, protocol and port) and generally offer around **5MB** of storage capacity per origin.
- **[`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage):** Data **persists indefinitely** until explicitly cleared via code or user action (such as clearing browser data). It is shared across all tabs and windows from the same origin.
- **[`sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage):** Data persists **only for the duration of the top-level page session.** If the user closes that specific tab or window, the session data is destroyed.

### Dynamic Cross-Tab Synchronisation ([`storage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event) event)

- Changes made to [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) in one tab automatically trigger a [`storage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event) event on the [`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) object of all **other** open tabs from the same origin.
- This enables real-time synchronisation (e.g., syncing user login state or themes across tabs).
- [`sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) does *not* trigger cross-tab events because it is isolated to a single tab.

### Security risks (XSS)
- Web storage is completely exposed to JavaScript execution within the page.
- If your site is vulnerable to [Cross-Site Scripting (XSS)](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/XSS) - where an attacker injects malicious scripts - the attacker can easily read everything in [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) or [`sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) using [`localStorage.getItem()`](https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem).
- Therefore, sensitive information (such as JWT access tokens or passwords) **typically shouldn&apos;t be stored here.**

**Example - Web storage and cross-tab events:**

```
// language: js
// 1. Storing and retrieving data
localStorage.setItem(&apos;username&apos;, &apos;Alice&apos;);
sessionStorage.setItem(&apos;tempSessionToken&apos;, &apos;xyz-123&apos;);

const user = localStorage.getItem(&apos;username&apos;); // &apos;Alice&apos;
console.log(user);

// 2. Listening for cross-tab storage changes
window.addEventListener(&apos;storage&apos;, (event) =&gt; {
  if (event.key === &apos;username&apos;) {
    console.log(`Username changed in another tab from &quot;${event.oldValue}&quot; to &quot;${event.newValue}&quot;`);
  }
});

// Removing items
localStorage.removeItem(&apos;username&apos;);
localStorage.clear(); // Wipes all localStorage for this origin
```

### Cookies and browser security

- HTTP cookies are **small pieces of data** traditionally used for **server-client communication** (such as session management, tracking and personalisation).

### Limitations of [`document.cookie`](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie)

- Interacting with cookies via the [`document.cookie`](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) API is **notoriously problematic.**
- It gets and sets cookies as a **single, raw semicolon-separated string** (e.g., `user=John;` `loggedIn=true;`).
- Meaning that there are **no built-in methods to easily query, update or delete individual cookies without custom parsing functions.**

### Cookie attributes for browser security

To protect cookies from attacks, modern web applications rely on strict security attributes:

1. **`HttpOnly`:** When set, the cookie cannot be accessed via client-side JavaScript ([`document.cookie`](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) will not show it). This is a critical defence mechanism against **XSS theft**, as malicious injected scripts cannot steal session cookies. (*This can only be set via HTTP headers from the server, not in JavaScript*)
2. **`Secure`:** This ensures that the cookie is only transmitted over encrypted connections (HTTPS), preventing interception via [Man-in-the-Middle (MitM)](https://www.imperva.com/learn/application-security/man-in-the-middle-attack-mitm/) attacks.
3. **`SameSite`:** Controls whether cookies are sent with cross-site requests to mitigate [Cross-Site Request Forgery (CSRF)](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF):
    - **`Strict`:** The cookie is **never sent in cross-site requests** (e.g., following a link from an external site).
    - **`Lax`:** The cookie is **withheld on cross-site sub-requests** (like images or IFrames), but sent when a user navigates to the origin site (e.g., following a link).
    - **`None:`** The cookie is sent in **all cross-site requests** (must be accompanied by the `Secure` attribute).

**Example - [`document.cookie`](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) usage:**

```
// language: js
// Setting a cookie with expiration, path, and security flags
document.cookie = &quot;username=Bob; max-age=3600; path=/; SameSite=Lax; Secure&quot;;

// Reading cookies (requires manual parsing)
const getCookie = (name) =&gt; {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(&apos;;&apos;).shift();
};

console.log(getCookie(&apos;username&apos;)); // &apos;Bob&apos;

// Deleting a cookie by setting its expiration date to the past
document.cookie = &quot;username=; max-age=0; path=/;&quot;;
```

### IndexedDB

[IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) is a low-level, client-side transactional database system built directly into the browser. Unlike key-value web storage which only stores strings, [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) can store large amounts of structured data, including complex JavaScript objects, files and large binary objects ([Blobs](https://developer.mozilla.org/en-US/docs/Web/API/Blob)), making it ideal for offline-first applications (e.g., [Progressive Web Apps](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps)).

#### Key concepts
1. **Asynchronous API:** Unlike [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) (which is synchronous and can therefore block the main thread if overloaded), IndexedDB operations are entirely asynchronous, using [`IDBRequest`](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest) objects, success/error callbacks or [Promises](https://www.taqtiq.tech/insights/javascript-mastering-the-event-loop-callbacks-and-asynchronous-code#the-shift-to-using-promises).
2. **Object Stores:** Similar to tables or collections in SQL/NoSQL databases, data is grouped into object stores.
3. **Transactions:** All read and write operations on IndexedDB must be performed within a transaction (`readonly` or `readwrite`) , ensuring data integrity and atomicity.
4. **Indices:** You can create indices on object store properties to enable fast, efficient querying and searching of records.

**Example - Opening IndexedDB and performing transactions:**

```
// language: js
// 1. Open (or create) a database
const request = indexedDB.open(&apos;MyOfflineDatabase&apos;, 1);

request.onupgradeneeded = (event) =&gt; {
  const db = event.target.result;
  // Create an object store with an auto-incrementing primary key &apos;id&apos;
  if (!db.objectStoreNames.contains(&apos;users&apos;)) {
    const store = db.createObjectStore(&apos;users&apos;, { keyPath: &apos;id&apos;, autoIncrement: true });
    // Create an index to search users quickly by email
    store.createIndex(&apos;email_idx&apos;, &apos;email&apos;, { unique: true });
  }
};

request.onsuccess = (event) =&gt; {
  const db = event.target.result;

  // 2. Write data using a &apos;readwrite&apos; transaction
  const transaction = db.transaction([&apos;users&apos;], &apos;readwrite&apos;);
  const store = transaction.objectStore(&apos;users&apos;);
  
  const addUserRequest = store.add({ name: &apos;Charlie&apos;, email: &apos;charlie@example.com&apos; });
  
  addUserRequest.onsuccess = () =&gt; {
    console.log(&apos;User added successfully to IndexedDB!&apos;);
  };

  // 3. Read data using an index
  const readTransaction = db.transaction([&apos;users&apos;], &apos;readonly&apos;);
  const readStore = readTransaction.objectStore(&apos;users&apos;);
  const emailIndex = readStore.index(&apos;email_idx&apos;);
  
  const getRequest = emailIndex.get(&apos;charlie@example.com&apos;);
  getRequest.onsuccess = () =&gt; {
    console.log(&apos;Found user:&apos;, getRequest.result);
  };
};

request.onerror = (event) =&gt; {
  console.error(&apos;IndexedDB error:&apos;, event.target.error);
};
```

### Comparison table

| Feature | [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) / [`sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) | Cookies | [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) |
| :--- | :--- | :--- | :--- |
| **Capacity** | ~5 MB | ~4 KB per cookie | Large (hundreds of MBs / GBs) |
| **Data Type** | Strings only | Strings only | Structured objects, Blobs, Files |
| **Execution** | Synchronous | Synchronous | Asynchronous |
| **Scope** | Origin-based | Path &amp; Domain-based | Origin-based |
| **Primary Use Case** | UI states, lightweight preferences | Server authentication, session IDs | Offline caching, heavy structured data |</content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript: Advanced Meta-Programming, Memory Management and Performance]]></title>
            <description><![CDATA[An overview of iterators, generators and lazy evaluation, meta-programming with proxies and the Reflect API, and memory management and garbage collection.]]></description>
            <link>https://www.taqtiq.tech/blog/javascript-advanced-meta-programming-memory-management-and-performance</link>
            <guid isPermaLink="false">j979njfger5rhw8px3wpd7vydd8hgyr4</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[tutorials]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 00:12:37 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/62ff5933-51f9-4395-8a54-e3998ca968e5" length="0" type="audio/mpeg"/>
            <content:encoded>## Iterators, Generators and Lazy Evaluation

### What is an iterator?

- In JavaScript, an iterator is an **object that defines a sequence, and potentially a return value upon its completion.**
- An iterator is **any object that implements the [iterator protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol)** by having a [`next()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#next) method.
- The [iterator protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol) standardises how a sequence of values is produced.
- An object is considered [iterable](https://www.w3schools.com/js/js_iterables.asp) if it implements the `Symbol.iterator` method.

### Iterables vs iterators

**Iterables and iterators can be easy to mix up.** Here is an easy way to think about the difference:

- **Iterable:** An object that **has** a sequence of data and wants to share it (like a book with pages, for instance).
- **Iterator:** An object that **does** the work of getting the next item from that sequence (like a bookmark keeping track of where you are).

#### 1. Iterables (the data source):
- An iterable is any JavaScript object that implements the [iterable protocol](https://codeblanks.com/courses/javascript/the-iterable-protocol).
- To be an iterable, an object must have a method with the special key `Symbol.iterator`.
- When called, this method returns a **new iterator.**
- Arrays, Strings, Maps, Sets and NodeLists are all built-in iterables.
- Plain JavaScript objects (`{}`) are **not** iterable by default.

**Example:**

```
// language: js
const numbers = [10, 20, 30]; // Array is an iterable

// You can access its Symbol.iterator method directly:
const iteratorMethod = numbers[Symbol.iterator];
console.log(typeof iteratorMethod); // &quot;function&quot;
```

#### 2. Iterators (the traverser):
- An iterator is an object that actually steps through the iterable.
- An iterator must have a  [`next()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#next) method.

#### The [`next()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#next) method returns an object with two properties:
1. [`value`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#value): The next value in the sequence.
2. [`done`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#done): A boolean that is `true` if the iterator has reached the end of the sequence or `false` if it has not.

When you call the [`next()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#next) method on an iterator, it steps through a collection one by one.

**Example 1:**

```
// language: js
const numbers = [10, 20];

// 1. Get the iterator from the iterable
const iterator = numbers[Symbol.iterator]();

// 2. Step through manually using .next()
console.log(iterator.next()); // { value: 10, done: false }
console.log(iterator.next()); // { value: 20, done: false }
console.log(iterator.next()); // { value: undefined, done: true }
```

**Example 2:**

```
// language: js
function makeIterator(array) {
  let nextIndex = 0;
  return {
    next: function() {
      if (nextIndex &lt; array.length) {
        return { value: array[nextIndex++], done: false };
      } else {
        return { value: undefined, done: true };
      }
    }
  };
}

const iterator = makeIterator([&apos;Apple&apos;, &apos;Banana&apos;, &apos;Cherry&apos;]);

console.log(iterator.next()); // { value: &apos;Apple&apos;, done: false }
console.log(iterator.next()); // { value: &apos;Banana&apos;, done: false }
console.log(iterator.next()); // { value: &apos;Cherry&apos;, done: false }
console.log(iterator.next()); // { value: undefined, done: true }
```

#### Comparison table

| Feature | Iterable | Iterator |
| :--- | :--- | :--- |
| **Analogy** | The entire playlist or book | The play/bookmark pointer tracking your current spot |
| **Key Property** | `[Symbol.iterator]` | `next()` |
| **Returns** | An **Iterator** | `{ value, done }` |
| **Examples** | `Array`, `String`, `Set`, `Map` | The object returned by calling `array[Symbol.iterator]()` |

### for...of loop

When you write a [`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) loop, JavaScript automatically coordinates the iterable and iterator behind the scenes, so [`next()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#next) doesn&apos;t have to be called manually.

**Example:**

```
// language: js
const colors = [&quot;red&quot;, &quot;blue&quot;];

for (const color of colors) {
  console.log(color);
}

// What JavaScript is actually doing under the hood:
const iterator = colors[Symbol.iterator]();
let result = iterator.next();

while (!result.done) {
  const color = result.value;
  console.log(color);
  result = iterator.next();
}
```

### Generator functions ([`function*`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*)) and bidirectional communication

- Generator functions (declared with  [`function*`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*)) simplify writing iterators.
- Instead of manually creating a function with a [`next()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#next) method, **you use the [`yield`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield) keyword to pause execution and emit a value.**

**Example:**

```
// language: js
function* numberGenerator() {
  yield 1;
  yield 2;
  yield 3;
}

const gen = numberGenerator();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }
```

- Generators don&apos;t just output data, they can receive data back *into* the [`yield`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield) expression through the arguments passed into `next(value)`.

**Example:**

```
// language: js
function* conversationalGenerator() {
  console.log(&quot;Generator started&quot;);
  
  const name = yield &quot;What is your name?&quot;;
  console.log(`Received name: ${name}`);
  
  const age = yield `Hello ${name}, how old are you?`;
  console.log(`Received age: ${age}`);
  
  return `${name} is ${age} years old.`;
}

const convo = conversationalGenerator();

// 1. Start the generator until the first yield
console.log(convo.next()); 
// Output: &quot;Generator started&quot;
// Output: { value: &quot;What is your name?&quot;, done: false }

// 2. Send data back into the first yield, run until the next yield
console.log(convo.next(&quot;Alice&quot;)); 
// Output: &quot;Received name: Alice&quot;
// Output: { value: &quot;Hello Alice, how old are you?&quot;, done: false }

// 3. Send data back into the second yield, finish execution
console.log(convo.next(25)); 
// Output: &quot;Received age: 25&quot;
// Output: { value: &quot;Alice is 25 years old.&quot;, done: true }
```

### Lazy evaluation

[Lazy evaluation](https://itnext.io/lazy-evaluation-in-javascript-62b8ec45e0f6) means computing values *on-demand* rather than ahead of time. This enables powerful design patterns like infinite streams and memory-efficient data processing.

### Infinite data streams

- Because generators pause execution, you can define infinite loops without the program crashing. Values are only generated when requested.

**Example:** 

```
// language: js
function* infiniteSequence() {
  let i = 1;
  while (true) {
    yield i++;
  }
}

const infiniteNumbers = infiniteSequence();

// We can safely grab just what we need
console.log(infiniteNumbers.next().value); // 1
console.log(infiniteNumbers.next().value); // 2
console.log(infiniteNumbers.next().value); // 3
// ...and so on, indefinitely.
```

### Custom data structures (e.g., tree traversal)

- Generators make complex traversals clean because you can yield values recursively using [`yield*`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield*).

**Example:**

```
// language: js
const tree = {
  value: 1,
  left: { value: 2, left: null, right: null },
  right: { value: 3, left: null, right: null }
};

function* traverseTree(node) {
  if (!node) return;
  yield node.value;
  yield* traverseTree(node.left);
  yield* traverseTree(node.right);
}

for (const val of traverseTree(tree)) {
  console.log(val); // Output: 1, 2, 3
}
```

### Asynchronous generators

- You can combine generators with [`async/await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) to stream data asynchronously (e.g., fetching  pages of an API lazily).

```
// language: js
async function* fetchPages() {
  let page = 1;
  let hasMore = true;

  while (hasMore) {
    // Simulating an asynchronous fetch request
    const data = await fakeApiFetch(page); 
    yield data.items;
    
    hasMore = data.hasMore;
    page++;
  }
}

// Consuming an async generator with for await...of
async function processPages() {
  for await (const items of fetchPages()) {
    console.log(&quot;Processed page items:&quot;, items);
  }
}
```

## Meta-programming with proxies and the Reflect API

### The [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) object

A [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) allows you to wrap an object and **intercept or redefine fundamental operations** (like getting a property, setting a property, validating data, or calling a function). 

**Example:**

```
// language: js
const target = { name: &quot;Alice&quot;, age: 30 };

const handler = {
  // Intercept property access (e.g., target.age)
  get(obj, prop) {
    console.log(`Getting property &quot;${prop}&quot;`);
    return prop in obj ? obj[prop] : &quot;Property does not exist&quot;;
  },
  
  // Intercept property assignment (e.g., target.age = 31)
  set(obj, prop, value) {
    if (prop === &apos;age&apos; &amp;&amp; typeof value !== &apos;number&apos;) {
      throw new TypeError(&quot;Age must be a number&quot;);
    }
    console.log(`Setting &quot;${prop}&quot; to ${value}`);
    obj[prop] = value;
    return true; // indicates success
  }
};

const proxyUser = new Proxy(target, handler);

console.log(proxyUser.name); // Logs interception, prints &quot;Alice&quot;
proxyUser.age = 35;          // Logs: Setting &quot;age&quot; to 35
```

### The Reflect API

The [`Reflect`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect) API is a built-in object that provides methods for interceptable JavaScript operations. It mirrors the traps of [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy). Whenever you intercept an operation with a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy), it is common practise to use [`Reflect`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect) to perform the default behaviour.

**Example:**

```
// language: js
const target = { x: 10, y: 20 };

const proxy = new Proxy(target, {
  get(target, prop, receiver) {
    console.log(`Tracking read for: ${prop}`);
    // Reflect handles the default lookup safely
    return Reflect.get(target, prop, receiver);
  }
});

console.log(proxy.x); // Tracks read, prints 10
```

### Real-world applications

#### 1. Observable state management (reactivity)

**Modern front-end frameworks (like Vue 3) use [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) under the hood to make application state &quot;reactive&quot;.** When a piece of data changes, the framework intercepts the write operation and automatically triggers [DOM](https://www.taqtiq.tech/insights/what-is-the-document-object-model-in-web-applications) updates or re-renders components.

**Example:**

```
// language: js
// A simple reactive state manager
function reactive(target, onChange) {
  return new Proxy(target, {
    set(obj, prop, value) {
      const oldValue = obj[prop];
      obj[prop] = value;
      
      // Only trigger if the value actually changed
      if (oldValue !== value) {
        onChange(prop, value, oldValue);
      }
      return true;
    }
  });
}

// Our application state
const state = reactive({ theme: &apos;light&apos;, count: 0 }, (prop, newValue, oldValue) =&gt; {
  console.log(`[UI Update] State property &apos;${prop}&apos; changed from &apos;${oldValue}&apos; to &apos;${newValue}&apos;`);
});

state.count = 1; // Triggers UI update log automatically!
state.theme = &apos;dark&apos;;
```

#### 2. Strict data validation and sanitisation

Proxies allow you to enforce schemas, data types, or boundaries dynamically without needing to write custom getters and setters for every single property on a class or object.

**Example:**

```
// language: js
const userValidatorHandler = {
  set(target, prop, value) {
    if (prop === &apos;age&apos;) {
      if (typeof value !== &apos;number&apos; || value &lt; 0 || value &gt; 120) {
        throw new RangeError(&quot;Age must be a valid number between 0 and 120.&quot;);
      }
    }
    if (prop === &apos;email&apos;) {
      if (!value.includes(&apos;@&apos;)) {
        throw new TypeError(&quot;Invalid email format.&quot;);
      }
    }
    
    target[prop] = value;
    return true;
  }
};

const user = new Proxy({}, userValidatorHandler);

user.email = &quot;test@example.com&quot;; // Works fine
// user.age = 150;               // Throws RangeError: Age must be a valid number...
```

#### 3. Auto-populating objects

Sometimes you want to automatically initialise missing keys when you try to read or write to them, preventing `undefined` errors. This is especially useful for nested structures, graphs, or caching layers.

**Example:**

```
// language: js
function autoVivification(target = {}) {
  return new Proxy(target, {
    get(obj, prop) {
      // If it&apos;s a built-in symbol (like iterator), let it pass through normally
      if (typeof prop === &apos;symbol&apos; || prop in obj) {
        return obj[prop];
      }
      
      // Automatically create a nested auto-populating object for missing properties
      obj[prop] = autoVivification();
      return obj[prop];
    }
  });
}

const nestedTree = autoVivification();

// Deeply nested assignment works seamlessly without checking if each level exists first
nestedTree.europe.france.capital = &quot;Paris&quot;;
console.log(nestedTree.europe.france.capital); // &quot;Paris&quot;
console.log(nestedTree.asia.japan.capital);    // Returns a new proxy object instead of undefined!
```

## Memory Management and Garbage Collection

- Modern JavaScript engines (such as [Google&apos;s V8](https://v8.dev/)) manage memory by dividing it into two primary areas:
1. The **stack**.
2. The **heap**.

### The stack
- A **structured**, fast memory region operating on [&quot;Last-In-First-Out&quot;](https://www.taqtiq.tech/insights/javascript-demystifying-execution-context-the-call-stack-and-the-this-keyword#what-is-last-in-first-out-lifo).
- It is responsible for **static memory allocation**, including [execution contexts](https://www.taqtiq.tech/insights/javascript-demystifying-execution-context-the-call-stack-and-the-this-keyword#what-is-an-execution-context), **pointer references** and **primitive values**.
- Allocating and clearing the stack is **extremely fast** because the size of primitives is **known** and **fixed** at compile time.

### The heap
- An **unstructured**, large memory pool used for **dynamic memory allocation** where data sizes can change or are **unknown ahead of time** (e.g., [`objects`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object), [`arrays`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) and [`functions`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions)). 
- Allocating memory **takes longer** because the engine as to search for a block of memory large enough to fit the data.

### Primitive vs reference value storage

- **Primitive values ([`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String), [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number), [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean), [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null), [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined), `symbol`, [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt))**: These are stored directly on the stack. When you assign a primitive to a new variable, a completely independent copy of that value is created.
- **Reference values ([`object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object), [`array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array), [`function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions)):** The actual data structure is stored on the heap, whereas a reference pointer to that heap address is stored on the stack. When an object is assigned to a new variable you are only copying the pointer. Both variables point to the exact same object in the heap. Modifying one will affect the other.

### Garbage collection algorithms

- **The engine runs automated processes to reclaim memory from objects that are no longer needed.**

### Mark-and-sweep algorithm
- This is the foundational algorithm used by [V8](https://v8.dev/).
- The algorithm goes through two phases:
1. A **mark phase.**
2. A **sweep phase.**
- The algorithm periodically starts from **roots** (global objects, currently active execution stacks/closures).
- It traverses down the reference graph, marking every object it can reach.
- During the sweep phase, any memory blocks that remain *unmarked* are deemed unreachable (garbage) and are reclaimed by the engine.

### Generational collection
- [V8](https://v8.dev/) optimises garbage collection based on the [&quot;weak generational hypothesis&quot;](https://v8.dev/blog/trash-talk#generational-layout) - the observation that **most objects die young**.

**The heap is split into:**

1. **The young generation (split further into &quot;nursery&quot; and &quot;intermediate&quot; generations):** This is where new objects are born. It is collected frequently using a fast [Scavenge algorithm (minor GC)](https://v8.dev/blog/trash-talk#minor-gc) that moves surviving objects between two semi-spaces.
2. **The old generation:** Objects that survive multiple young generation sweeps are placed here. It is collected less frequently using a [Mark-Sweep-Compact algorithm (major GC)](https://v8.dev/blog/trash-talk#major-gc-state).

### Optimisation strategies

- Engines use [hidden classes (shapes)](https://dev.to/maxprilutskiy/hidden-classes-the-javascript-performance-secret-that-changed-everything-3p6c) and [inline caching](https://medium.com/@conboys111/how-javascript-engines-use-inline-caching-to-optimize-your-code-aaf94d3d1801) to speed up property lookups on dynamic objects, **reducing the overhead required during execution and memory traversal.**

### Memory leaks

- [Single Page Applications (SPAs)](https://developer.mozilla.org/en-US/docs/Glossary/SPA) run for long periods of time in a browser session. This can make them prone to [memory leaks](https://medium.com/@simplycodesmart/understanding-and-preventing-memory-leaks-in-javascript-1a6fc5d9f4f5) if references to unused objects are unintentionally retained.

#### Common causes of memory leaks

- **Accidental globals:** Forgetting to declare a variable with [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const), [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let), or [`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) implicitly attaches it to the global window object - **meaning it will never be garbage collected.**
- **Forgotten event listeners:** Attaching event listeners to global elements (like [`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window), [`document`](https://developer.mozilla.org/en-US/docs/Web/API/Document) or large parent containers) and failing to remove them ([`removeEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener)) when components unmount keeps the target elements and their outer scopes trapped in memory.
- **Detached DOM nodes:** Storing a reference to a [DOM](https://www.taqtiq.tech/insights/what-is-the-document-object-model-in-web-applications) element in a JavaScript [`array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) or [`object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object), and later removing that element from the document tree.
- **Closure retention:** Inner functions that retain references to outer scope variables long after the outer function has returned can accidentally trap heavy data structures if not scoped properly.

### Using Chrome DevTools memory profiler to address memory leaks

To address memory leaks you can:

1. Open **Chrome DevTools** and navigate to the **Memory** tab.
2. Take a **Heap Snapshot** before performing an action (e.g., opening and closing a modal).
3. Perform an action and take another snapshot.
4. Compare snapshots using the **Comparison** view or filter by **Detached Elements** to look for DOM nodes that should have been garbage collected.
5. Inspect the **Retainer Tree** to trace *why* an object is alive (which variable or listener is holding on to the reference), then you can clean up the reference in your code.</content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript: Objects, Prototypes and Object-Oriented Programming]]></title>
            <description><![CDATA[A deep dive into how JavaScript approaches object-oriented programming, with a comparison of inheritance vs composition in JavaScript.]]></description>
            <link>https://www.taqtiq.tech/blog/javascript-objects-prototypes-and-object-oriented-programming</link>
            <guid isPermaLink="false">j976x018g4mw6d3pgvdkww537h8gwppb</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[tutorials]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 16:02:27 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/32ddc257-61d1-4122-9e71-3bf80c938b56" length="0" type="audio/mpeg"/>
            <content:encoded>## Objects

### What is an [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)?

&gt; An object is a collection of properties, and a property is an association between a name (or key) and a value.

[&apos;Working with Objects&apos; - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_objects)

- In JavaScript, **almost everything is an object.**
- At its core, an object is a **standalone collection of related data and/or functionality, consisting of key-value pairs** (known as **properties** and **methods**).

![Objects](/api/storage/kg21r4ar36rbx3xckg3rfcv0n98gybg5)

### Anatomy of an object
- An object literal is **wrapped in curly braces** (`{}`) and contains **comma-separated key-value pairs:**
```
// language: js
const user = {
  // Properties (Data)
  firstName: &quot;Jane&quot;,
  lastName: &quot;Doe&quot;,
  age: 28,
  isSubscriber: true,

  // Method (Function attached to an object)
  getFullName: function() {
    return `${this.firstName} ${this.lastName}`;
  }
};
```

- Keys are stored as [strings](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) (or symbols).
- Values can be any data type (e.g., [strings](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String), [numbers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number), [booleans](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean), [arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array), [functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions), or even other **nested objects**.)
- [The](https://www.taqtiq.tech/insights/javascript-demystifying-execution-context-the-call-stack-and-the-this-keyword#what-is-the-this-keyword) [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) [keyword refers to the current object context, allowing methods to access the object&apos;s properties.](https://www.taqtiq.tech/insights/javascript-demystifying-execution-context-the-call-stack-and-the-this-keyword#what-is-the-this-keyword)

### Accessing and modifying properties of an object
There are **two different syntaxes for accessing the properties of an object:**

#### The **dot notation (`.`):**
```
// language: js
console.log(user.firstName); // &quot;Jane&quot;
user.age = 29; // Modifying a property
```

#### The **bracket notation (`[...]`):**
```
// language: js
console.log(user[&quot;lastName&quot;]); // &quot;Doe&quot;
const propertyKey = &quot;isSubscriber&quot;;
console.log(user[propertyKey]); // true
```
- Allows dynamic keys, spaces, or special characters via strings or variables.

### Creating objects
- Other than object literals (`{}`), in JavaScript there are various different ways to instantiate objects:

| Method | Example | Use Case |
| :--- | :--- | :--- |
| **Object Literal** | `const obj = { name: &quot;Test&quot; };` | Quick, one-off collections of data. |
| [`new Object()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new) | `const obj = new Object(); obj.name = &quot;Test&quot;;` | Rarely used explicitly; mostly historical. |
| **Constructor Functions** | `function Car(make) { this.make = make; }` | Pre-ES6 blueprinting for multiple instances. |
| **Classes ([ES6](https://www.w3schools.com/js/js_es6.asp)+)** | `class Car { constructor(make) { this.make = make; } }` | Modern, clean blueprinting using OOP syntax. |
| [`Object.create()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create) | `const obj = Object.create(proto);` | Direct prototype inheritance setup. |

## Prototypes and inheritance 

### What is a prototype?
&gt; Prototypes are the mechanism by which JavaScript objects inherit features from one another.

[&apos;Prototypes&apos; - MDN](https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/Advanced_JavaScript_objects/Object_prototypes)

- JavaScript is a **prototype-based language.**
- This means that JavaScript **handles inheritance differently from classic object-oriented languages like Java, C++ or Python.**
- Instead of inheriting from &quot;classes&quot; that act as rigid blueprints, **JavaScript objects inherit directly from other objects.**
- Every object in JavaScript has a **hidden internal property** (historically referred to as `[[prototype]]` or accessed via [`__proto__`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto)) that **links to another object called its *prototype***.

### The prototype chain

&gt; 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.

[&apos;Inheritance and the prototype chain&apos; - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain)

When you try to access a property or method on an object:

1. JavaScript will first **check the object itself for that property/method.** If it is there, it will use it.
2. If not, it **looks up the prototype link to the other object&apos;s prototype ([`__proto__`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto)).**
3. If it is not there again, it will **check *that* objects prototype, continually moving up the chain until it reaches `Object.prototype` whose prototype is [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null).**

![Prototype Chain](/api/storage/kg29836hh8pzps6rw62p1dj8298gydc5)

#### Code example:

```
// language: js
// 1. Define a constructor function
function Animal(name) {
  this.name = name;
}

// 2. Add a method to the prototype so all instances share it
Animal.prototype.speak = function() {
  return `${this.name} makes a noise.`;
};

// 3. Create an instance
const dog = new Animal(&apos;Rex&apos;);

// dog itself has &apos;name&apos;, but not &apos;speak&apos;
console.log(dog.hasOwnProperty(&apos;name&apos;));  // true
console.log(dog.hasOwnProperty(&apos;speak&apos;)); // false

// Yet, dog can call speak() via the prototype chain
console.log(dog.speak()); // &quot;Rex makes a noise.&quot;
```
## Object-Oriented JavaScript

### Prototypes vs [ES6](https://www.w3schools.com/js/js_es6.asp) [classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)

- When the [`class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) syntax was introduced in [ES6](https://www.w3schools.com/js/js_es6.asp), **it didn&apos;t add a traditional class-based inheritance model** (as seen in other programming languages like Java, C++, Python, etc).
- Instead, the [`class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) keyword is just [syntactic sugar](https://www.lenovo.com/gb/en/glossary/syntactic-sugar/?orgRef=https%253A%252F%252Fwww.google.com%252F&amp;srsltid=AU7gw4WT7ptIVJdMqiqHlgxWJG4sJ69Y2mp41IygguF4rQXm1TyPE84C) built on top of JavaScript&apos;s existing prototype-based system.

```
// language: js
// Modern class syntax...
class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    return `${this.name} makes a noise.`;
  }
}

// ...does the exact same thing as the earlier prototype example 

```

### The [`extends`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/extends) keyword

- The [`extends`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/extends) keyword is used in class declarations or class expressions to create a **child class that inherits all the properties and methods of the parent class.**
- It sets up the prototype chain so that **instances of the child class have access to the parent class’s methods.**

![Inheritance](/api/storage/kg21wx2n4qr00e4grp0pwmy4zn8gz349)

**Example:**

```
// language: js
class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

// Dog inherits from Animal using &apos;extends&apos;
class Dog extends Animal {
  bark() {
    console.log(`${this.name} barks!`);
  }
}

const myDog = new Dog(&quot;Rex&quot;);
myDog.speak(); // Output: Rex makes a sound. (Inherited from Animal)
myDog.bark();  // Output: Rex barks! (Defined on Dog)
```

### The [`super`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super) keyword

The [`super`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super) keyword serves **two purposes depending on where it is being used:**

#### When it is used in a constructor (calling the parent constructor)

- When a child class defines its own constructor, **it *must* call [`super`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super) before it can use the this keyword.**
- JavaScript requires the **parent class to initialise its own inherited properties first.** Passing arguments into super(...) forwards them to the parent class’s constructor.

### Getters and Setters

&gt; JavaScript getters and setters are special methods used to access and update object properties. They provide a controlled way to read and modify values.

[&apos;JavaScript Getters and Setters&apos; - GeeksforGeeks](https://www.geeksforgeeks.org/javascript/javascript-getters-and-setters/)

- Instead of directly interacting with a raw variable, **getters and setters let you intercept the read (getting) and write (setting) operations.**
- **They use the [`get`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get) and [`set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) keywords.**

#### Why use them?
- **Data Validation:** You can ensure that assigned values **meet certain conditions** (e.g., a user&apos;s age cannot be negative).
- **Computed Properties:** You can **dynamically calculate a value on the fly** whenever it&apos;s requested rather than storing it statically.
- **Encapsulation:** You can **hide internal implementation details** while presenting a clean property interface to the outside code.

**Example - Validation:**

```
// language: js
const user = {
  name: &quot;Alice&quot;,
  _age: 25, // Convention: underscore indicates an internal/private-like property

  // Getter: runs when you read user.age
  get age() {
    return this._age;
  },

  // Setter: runs when you assign a value like user.age = 30
  set age(value) {
    if (value &lt; 0) {
      console.log(&quot;Age cannot be negative!&quot;);
      return;
    }
    this._age = value;
  }
};

// Accessing the getter (notice it looks like a normal property, not a function call)
console.log(user.age); // 25

// Trying to set a valid age
user.age = 30;
console.log(user.age); // 30

// Trying to set an invalid age
user.age = -5; // Logs: &quot;Age cannot be negative!&quot;
console.log(user.age); // Stays 30
```

**Example - Computed Properties:**

```
// language: js
const rectangle = {
  width: 10,
  height: 5,

  // Computed getter for area
  get area() {
    return this.width * this.height;
  }
};

console.log(rectangle.area); // 50

// If dimensions change, the area updates automatically
rectangle.width = 20;
console.log(rectangle.area); // 100
```

**Example - Getters and Setters with classes:**

```
// language: js
class Temperature {
  constructor(celsius) {
    this._celsius = celsius;
  }

  get celsius() {
    return this._celsius;
  }

  set celsius(value) {
    this._celsius = value;
  }

  // Getter for Fahrenheit computed from Celsius
  get fahrenheit() {
    return (this._celsius * 9/5) + 32;
  }

  set fahrenheit(value) {
    this._celsius = (value - 32) * 5/9;
  }
}

const temp = new Temperature(25);
console.log(temp.fahrenheit); // 77

temp.fahrenheit = 212;
console.log(temp.celsius);    // 100
```

### Encapsulation and private fields

&gt; Encapsulation is the packing of data and functions into one component (for example, a class) and then controlling access to that component to make a &quot;blackbox&quot; out of the object. Because of this, a user of that class only needs to know its interface (that is, the data and functions exposed outside the class), not the hidden implementation.

[&apos;Encapsulation&apos; - MDN](https://developer.mozilla.org/en-US/docs/Glossary/Encapsulation)

- To put it simply, encapsulation is about **bundling data and the methods that operate on that data within a single unit (an object) and restricting direct access to some of the objects internal components.**

**Encapsulation gives you:**
- **Data Protection:** Prevents external code from accidentally breaking an objects internal logic.
- **Controlled Access:** Enforces validation rules (e.g., ensuring an age cannot be a negative number) via methods or getters/setters.
- **Abstraction:** Exposes only what other developers need to use 

### Encapsulation pre-[ES2022](https://www.w3schools.com/js/js_2022.asp)

Before native private fields were introduced, JavaScript developers relied on **conventions** and **closures** to hide data.

#### The underscore convention (`_`)
- Developers would use the `_` convention to indicate not to use particular properties.

**Example:**

```
// language: js
class User {
  constructor(name, password) {
    this.name = name;
    this._password = password; // Convention: &quot;Please don&apos;t touch this&quot;
  }
}

const user = new User(&quot;Alice&quot;, &quot;secret123&quot;);
console.log(user._password); // &quot;secret123&quot; — It is not actually private!
```

- The issue was that the field was **not actually hidden**. Nothing was actually preventing external code from reading or altering the property.

#### Closures and factory functions
- To truly hide fields, developers would use function **scopes** and **closures.**

**Example:**

```
// language: js
function createUser(name, password) {
  let _password = password; // Local variable, hidden from the outside

  return {
    name,
    getPassword() {
      return _password; // Accessible only through this closure
    }
  };
}

const user = createUser(&quot;Alice&quot;, &quot;secret123&quot;);
console.log(user._password); // undefined
console.log(user.getPassword()); // &quot;secret123&quot;
```

- The issue with this pattern is that **every instance duplicates the methods in memory,** which can be inefficient for large applications compared to prototype methods.

### Native [private fields](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_elements)

JavaScript introduced a native syntax for private **fields**, **methods** and **static members** using the hash (`#`) prefix.

&gt; Private elements get created by using a hash # prefix and cannot be legally referenced outside of the class.

&gt; The privacy encapsulation of these class elements is enforced by JavaScript itself. 

&gt; The only way to access a private element is via dot notation, and you can only do so within the class that defines the private element.

[&apos;Private Elements&apos; - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_elements)

**Example:**

```
// language: js
class BankAccount {
  #balance; // Declare private field at the class level

  constructor(owner, initialBalance) {
    this.owner = owner;
    this.#balance = initialBalance;
  }

  deposit(amount) {
    if (amount &gt; 0) {
      this.#balance += amount;
    }
  }

  getBalance() {
    return this.#balance;
  }
}

const account = new BankAccount(&quot;Alice&quot;, 1000);
account.deposit(500);
console.log(account.getBalance()); // 1500

// Trying to access #balance directly throws a SyntaxError!
// console.log(account.#balance);
```
#### Rules of private fields:

1.  **Declaration is mandatory:** **Private fields *must* be declared at the top of the class body (e.g., `#balance;`).** You cannot dynamically create them inside methods or constructor arguments without declaring them first.
2. **Strict runtime enforcement:** Attempting to access or modify a private field outside of the class body results in a syntax error.
3. **Private methods and static fields:** You can also make methods and static properties private.

**Example:**

```
// language: js
class Database {
  static #connectionLimit = 10; // Private static field

  #validateQuery(query) { // Private method
    return query.length &gt; 0;
  }

  executeQuery(query) {
    if (this.#validateQuery(query)) {
      return &quot;Executing...&quot;;
    }
  }
}
```

## Inheritance vs Composition

One of the most famous architectural debates in software engineering is **inheritance vs composition.** While JavaScript historically leaned into prototypal delegation that *looked* like classical inheritance (especially with the introduction of [ES6](https://www.w3schools.com/js/js_es6.asp) class syntax), modern JavaScript development **heavily favours composition.**

### &quot;Is-A&quot; vs &quot;Has-A&quot; or &quot;Can-Do&quot;

- To understand the core difference between inheritance and composition we can look at how each model **answers the question of relationship:**
- **Inheritance (&quot;Is-A&quot;):** A subclass is a specialised version of a superclass.
    - **Example:** A `Dog` *is an* `Animal`. A `Manager` *is an* `Employee`.
- **Composition (&quot;Has-A&quot; or &quot;Can-Do&quot;):** An object is built by combining independent, modular pieces of behaviour or smaller objects.
    - **Example:** A `Robot` *has a* `battery`, *has a* `navigationSystem`, and *can* `walk`. It doesn&apos;t inherit from a generic `Machine` tree - it is assembled from parts.

### The problem with classic inheritance

Inheritance feels intuitive at first because it easily maps on to real world taxonomies. However, as applications grow, deep inheritance hierarchies begin to cause severe maintenance issues.

Issues with deep inheritance:

- **Tight coupling:** Subclasses are deeply bound to their parent classes. Changing a method deep in the superclass can inadvertently break dozens of subclasses.
- **The Fragile Base Class Problem:** If a base class is modified by adding a new method or property, it can clash with existing subclass methods or introduce unexpected behaviors.  
- **Inflexible Taxonomies (The &quot;Flying Dog&quot; Dilemma):**
Imagine you start with a class hierarchy: `Animal` &amp;rarr; `Bird` (adds `fly()`) and `Animal` &amp;rarr; `Dog` (adds `bark()`). What happens when you need to create a `RobotDog` that can `walk` and `talk`, or a `FlyingSquirrel` that can `glide`, or a `SuperHero` that inherits traits from both `human` and `bird`? Inheritance forces you into rigid, single-parent hierarchies that cannot easily accommodate cross-cutting behaviours.

### Object composition

&gt; Composition in JavaScript is an object-oriented programming concept in which one object is built using other objects as its parts. It represents a strong “has-a” relationship, where the contained objects are closely tied to the lifecycle of the parent object.

[&apos;Composition in JavaScript&apos; - GeeksforGeeks](https://www.geeksforgeeks.org/javascript/composition-in-javascript/)

Instead of asking **&quot;What is this object?&quot;**, composition asks **&quot;What does this object do?&quot;** or **&quot;What parts make up this object?&quot;**.

![Composite Objects](/api/storage/kg29a5k0aqdw0c2gdgcjw7hrcn8gzt8m)

- In JavaScript, because objects are dynamic collections of key-value pairs, you can easily assemble objects by mixing and matching independent functions.

### Factory functions and object spreading

- Instead of [`class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) and [`extends`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/extends), you can use plain functions that return objects, combining behaviours using the [spread operator (`...`)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax).

```
// language: js
// 1. Define independent behavior functions (traits/mixins)
const canFly = (state) =&gt; ({
  fly: () =&gt; console.log(`${state.name} is flying!`)
});

const canSwim = (state) =&gt; ({
  swim: () =&gt; console.log(`${state.name} is swimming!`)
});

const canBark = (state) =&gt; ({
  bark: () =&gt; console.log(`${state.name} says Woof!`)
});

// 2. Compose them into specific creator functions
function createFlyingDog(name) {
  let state = { name };
  
  return {
    ...state,
    ...canFly(state),
    ...canBark(state)
  };
}

// 3. Usage
const mutantDog = createFlyingDog(&quot;Bolt&quot;);
mutantDog.bark(); // Bolt says Woof!
mutantDog.fly();  // Bolt is flying!
```

### Functional [mixins](https://developer.mozilla.org/en-US/docs/Glossary/Mixin)

- You can create functional [mixins](https://developer.mozilla.org/en-US/docs/Glossary/Mixin) - functions that take an object, argument it with new methods and return it.

```
// language: js
const withFlying = (target) =&gt; {
  target.fly = function() {
    console.log(`${this.name} is soaring through the clouds.`);
  };
  return target;
};

const withCombat = (target) =&gt; {
  target.attack = function() {
    console.log(`${this.name} attacks with power!`);
  };
  return target;
};

// Creating a character using composition
const warrior = withCombat({ name: &quot;Arthur&quot; });
warrior.attack(); // Arthur attacks with power!
```

### Summary table: inheritance vs composition

| Feature | Inheritance ([`class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) / [`extends`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/extends)) | Composition (Mixins / Factories) |
| :--- | :--- | :--- |
| **Relationship** | &quot;Is-A&quot; (Hierarchical) | &quot;Has-A&quot; or &quot;Can-Do&quot; (Flat) |
| **Flexibility** | Rigid; hard to change parent structure later. | High; mix and match behaviors dynamically. |
| **Reusability** | Limited to single-parent inheritance chains in JS. | Infinite; combine any number of behaviors. |
| **Maintenance** | Prone to the fragile base class problem. | Isolated; changing a trait only affects objects using it. |
| **JavaScript Idiom** | Syntactic sugar over prototypes. | Native alignment with JS&apos;s dynamic object model. |

- **Inheritance should be used sparingly** when you have a **genuine**, **shallow** &quot;Is-A&quot; relationship.
- **For almost everything else, you should be using composition** with factory functions or [mixins](https://developer.mozilla.org/en-US/docs/Glossary/Mixin).</content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript: Mastering the Event Loop, Callbacks and Asynchronous Code]]></title>
            <description><![CDATA[A look at the problem with single-threaded synchronous code, how JavaScript handles it and explaining the event loop, callbacks and asynchronous code.]]></description>
            <link>https://www.taqtiq.tech/blog/javascript-mastering-the-event-loop-callbacks-and-asynchronous-code</link>
            <guid isPermaLink="false">j972teqz1c958dr6k69qmef28d8gckxr</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[tutorials]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Fri, 16 Oct 2026 18:07:57 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/701b616a-8b70-4cc2-835e-93ce7c891fcc" length="0" type="audio/mpeg"/>
            <content:encoded>## The problem with single-threaded synchronous code

- JavaScript is [single-threaded](https://medium.com/@sweetondonie/single-thread-vs-multi-thread-a-beginners-guide-becc77c66a0c).
- JavaScript uses a [call stack](https://www.taqtiq.tech/insights/javascript-demystifying-execution-context-the-call-stack-and-the-this-keyword#what-is-the-call-stack) to execute code line by line ([synchronously](https://www.mendix.com/blog/asynchronous-vs-synchronous-programming/)).

![JavaScript Call Stack](/api/storage/kg2eadkf7yfcwpa64hq27zwhbh8gyx95)

![JavaScript Call Stack 2](/api/storage/kg2avqc7grv8th9v0btgtwvr1s8gznwp)

- The problem is that this causes a **major bottleneck** in how JavaScript functions. Especially when handling **heavy or slow operations.**
- If we ran all our operations on the main thread, the **entire application would freeze while we waited for the current action to complete.**
- This is because there is only one thread, so that thread would be **blocked while we process the current action.**

![If JavaScript Ran Everything on the Main Thread](/api/storage/kg22zavcm8kkznrqjqd9x3xkks8gyac5)

## Delegation
- JavaScript **doesn&apos;t work alone.**
- Instead, it runs inside a **host environment (such as the browser or Node.js).**

&gt; The JavaScript engine implements the ECMAScript (JavaScript) language, providing the core functionality. It takes source code, parses it, and executes it. However, in order to interact with the outside world, such as to produce any meaningful output, to interface with external resources, or to implement security- or performance-related mechanisms, we need additional environment-specific mechanisms provided by the host environment.

&gt; For example, the HTML DOM is the host environment when JavaScript is executed in a web browser. Node.js is another host environment that allows JavaScript to be run on the server side.

[The Engine and the Host - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Execution_model#the_engine_and_the_host)

- One way that JavaScript solves the aforementioned dilemma with synchronous code is by **delegating long-running or delayed tasks to the browser**  with **Web APIs** ([Web APIs - W3Schools](https://www.w3schools.com/js/js_api_intro.asp), [Web APIs - MDN](https://developer.mozilla.org/en-US/docs/Web/API)) (such as [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout), [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch) or [DOM event](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Events) listeners), freeing up its own call stack to keep other code running smoothly.

### What are Web APIs?
- Essentially, Web APIs are extra toolsets built directly into your web browser. **They are not part of core JavaScript (ECMAScript)**; instead, they are written in lower-level languages (like C++) by browser vendors (Google, Mozilla, Apple) and provided to JavaScript as global objects.

### How does JavaScript delegate with Web APIs?
- Whenever JavaScript hits a Web API (like [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout), for instance), **it immediately hands it off to the browsers Web API environment.**
- Once handed over, [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout) is **popped off the call stack** and JavaScript moves on to execute the next line of code. 
- JavaScript **does not wait for the timer to elapse before moving on.** It just hands the timer off to the Web API environment and continues. 

![How JavaScript handles setTimeout](/api/storage/kg25cyfgh66e5p08yw6exsp6ed8gz9g6)

- While the main JavaScript code continues running on the call stack, the browsers Web API **works on the delegated tasks in the background.**
- Crucially, the browser is **multi-threaded.** This means that the browser can **track multiple tasks at once.**

## What happens when the delegated tasks finish?

- After some time, the tasks that were delegated finish:

1. The timer for [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout) elapses.
2. The server sends back a response from the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch) request.
3. The DOM event finishes.

- When a task like [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout) completes, JavaScript **cannot immediately push the [callback function](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function) straight back onto the call stack.**
- This is because the call stack might **currently be busy with other synchronous code.**
- Instead, the [callbacks](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function) are **sent to one of two different queues, based on the priority level of the task.**

### The macrotask queue
This is commonly called the task queue or just the callback queue.

- **This is the standard queue.**
- Tasks **sit in the order they finish** and have to **wait their turn behind whatever is currently happening.**
- Tasks that go here:
    - **Callbacks from timers** ([`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout), [`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/Window/setInterval))
    - **I/O operations** and **network responses.**
    - **UI rendering** and **event listeners** (such as clicks, scrolls, keyboard inputs).

### The microtask queue
This is the high priority lane.

- Microtasks are created when something **needs to happen *immediately* after the but before the browser does anything else** (like rendering or running the next timer).
- Tasks that go here:
    - Callbacks from resolved or rejected [`Promises`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) (via [`.then()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then), [`.catch()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch), or [`.finally()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally))
    - [`async/await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) continuations (everything after an [`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) keyword runs as a microtask).
    - [`queueMicrotask`](https://developer.mozilla.org/en-US/docs/Web/API/Window/queueMicrotask)
    - [`MutationObserver`](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver)

## What is the [Event Loop](https://medium.com/@ignatovich.dm/the-javascript-event-loop-explained-with-examples-d8f7ddf0861d)?

- At its core, the JavaScript event loop is **responsible for managing the execution of code, collecting and processing events, and executing queued tasks.**
- The event loop is essentially an **infinite loop** running in the background whose **sole task is to monitor the call stack and the queues.**
- The event loop cycle looks like this:
    1. **Is the call stack empty?**
    2. If so, check the microtask queue. **Execute *all* tasks in the queue until it is empty.**
    3. Render UI updates.
    4. **Take the *single* oldest task from the macrotask queue, push it onto the call stack and execute it.**

![Event Loop](/api/storage/kg23e2db61454ysthcz9b55cn98gzcm6)

## [Callback hell](https://www.geeksforgeeks.org/javascript/what-is-callback-hell-in-javascript/)

- Before [ES6](https://www.w3schools.com/js/js_es6.asp), asynchronous operations in JavaScript **relied almost entirely** on [callback functions](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function).
- This lead to a common problem developers would call [&apos;callback hell&apos;](https://www.geeksforgeeks.org/javascript/what-is-callback-hell-in-javascript/), where **deeply nested code** would become **extremely difficult to read, maintain, and debug** as tasks depend on previous tasks.
- Example:

```
// language: js
getUserData(userId, function(user) {
    getOrders(user.id, function(orders) {
        getOrderDetails(orders[0].id, function(details) {
            console.log(details);
        });
    });
});
```

![The Pyramid of Doom](/api/storage/kg2fhne2jzbmsjntpy6mf5erwd8gza14)

- This would also lead to [&apos;Inversion of Control&apos;](https://medium.com/@carlmobarezi/inversion-of-control-in-javascript-callbacks-why-promises-are-the-answer-8813ab54789e) where **control over the flow of the program is handed off to external libraries or frameworks.**
- It would also make **error handling a nightmare** because every level of nesting would require its own [`try/catch`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) block.

## The shift to using [`Promises`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)

- [ES6](https://www.w3schools.com/js/js_es6.asp) introduced [`Promises`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which solved the problem of callback hell.
- A promise is a JavaScript [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) that acts as a placeholder for a **value that is not available yet.**
- A promise can be in one of three **mutually exclusive** states:
    1. **Pending:** Initial state, the asynchronous operation is still in progress.
    2. **Fulfilled (Resolved):** The operation completed successfully, producing a value.
    3. **Rejected:** The operation failed, returning a reason/error.

Once a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) moves from `Pending` to either `Fulfilled` or `Rejected` it is **settled** and can **never change its state again.**

[`Promises`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) solve the [&apos;Inversion of Control&apos;](https://medium.com/@carlmobarezi/inversion-of-control-in-javascript-callbacks-why-promises-are-the-answer-8813ab54789e) issue by **guaranteeing that the success or error handler is called exactly once.**

### The pyramid of doom is flattened

- Promises allow you to chain operations sequentially using [`.then()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then), [`.catch()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch), and [`.finally()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally):

```
// language: js
getUserData(userId)
    .then(user =&gt; getOrders(user.id))
    .then(orders =&gt; getOrderDetails(orders[0].id))
    .then(details =&gt; console.log(details))
    .catch(error =&gt; console.error(&quot;An error occurred:&quot;, error));
```

### How do [`Promises`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) work behind the scenes?

- When a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) resolves or rejects:
    1. Its [`.then()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then), [`.catch()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch), or [`.finally()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally) callbacks are **pushed to the microtask queue.**
    2. This guarantees that [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) callbacks **execute immediately after the current stack clears**, taking precedence over [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout) or network events in the Macrotask Queue.

## [`async`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) and [`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)
- [`async`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) and [`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) were introduced in [ES2017](https://www.w3schools.com/js/js_2017.asp).
- [`async`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) and [`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) do not replace [`Promises`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), they are syntactic sugar built directly on top of [`Promises`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).

&gt; Syntactic sugar refers to certain language features in programming that make the code easier to read or write. It&apos;s like adding a bit of sweetness to your code syntax to make it more pleasant to work with.

[Syntactic Sugar - Lenovo](https://www.lenovo.com/gb/en/glossary/syntactic-sugar/?orgRef=https%253A%252F%252Fwww.google.com%252F&amp;srsltid=AU7gw4WT7ptIVJdMqiqHlgxWJG4sJ69Y2mp41IygguF4rQXm1TyPE84C)

- [`async`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) and [`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) **allow you to write asynchronous code that reads just like synchronous code**, without blocking the main thread.
- Example:

```
// language: js
async function fetchDetails(userId) {
    try {
        const user = await getUserData(userId);
        const orders = await getOrders(user.id);
        const details = await getOrderDetails(orders[0].id);
        console.log(details);
    } catch (error) {
        console.error(&quot;An error occurred:&quot;, error);
    }
}
```

### How do [`async`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) and [`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) work behind the scenes?

[`async`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)

- [`async`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) **functions always return a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).**
- Marking a function as [`async`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) **guarantees that its return value will automatically be wrapped in a resolved Promise.**

[`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)

- The [`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) keyword **pauses function execution.**
- When the JavaScript engine encounters [`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function):
    1. **It pauses the execution of *that specific* [`async`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) function.**
    2. It takes the remaining execution of that function and **packages it as a microtask callback attached to the [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) being awaited.**
    3. It **yields control back to the main call stack**, allowing other synchronous code or UI renders outside the function to continue running.

Once the awaited [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) resolves, the remainder of the [`async`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) function is pushed onto the microtask stack and resumes execution on the stack.

### Summary table
| Feature | Callbacks | Promises | [`async/await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) |
| :--- | :--- | :--- | :--- |
| **Syntax Style** | Nested callbacks | Method chaining ([`.then()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then)) | Sequential / Imperative |
| **Queue Used** | Macrotask or Microtask (varies) | **Microtask Queue** | **Microtask Queue** |
| **Error Handling** | Manual per callback | [`.catch()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch) block | Native [`try/catch`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) blocks |
| **Readability** | Poor (&quot;Pyramid of Doom&quot;) | Medium (Chained) | Excellent (Reads like sync code) |</content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript: Demystifying Execution Context, the Call Stack and the 'this' Keyword]]></title>
            <description><![CDATA[An overview of how execution context the call stack and the 'this' keyword work in JavaScript, with a note on how arrow functions handle 'this'.]]></description>
            <link>https://www.taqtiq.tech/blog/javascript-demystifying-execution-context-the-call-stack-and-the-this-keyword</link>
            <guid isPermaLink="false">j973hqs172w1546xvaxzhvrm0d8gaw6w</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[tutorials]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 00:34:01 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/4cbbc29a-0024-499f-a413-e304e5b9a012" length="0" type="audio/mpeg"/>
            <content:encoded>## How does JavaScript code run?

To understand how JavaScript code runs, you first need to understand what [&apos;execution context&apos;](https://www.freecodecamp.org/news/how-javascript-works-behind-the-scene-javascript-execution-context/) is.

### What is an [&apos;execution context&apos;](https://www.freecodecamp.org/news/how-javascript-works-behind-the-scene-javascript-execution-context/)?

&gt; An execution context is a specification device that is used to track the runtime evaluation of code by an ECMAScript implementation.

[&apos;Execution Contexts&apos; - ECMAScript Language Specification](https://262.ecma-international.org/#sec-execution-contexts)

- To put it in simpler terms, an execution context is an internal box created by JavaScript that holds all the information needed to run a specific piece of code.

### What are the different types of execution contexts?

- Whenever code runs in JavaScript, **it only ever runs in one of three types of execution contexts:**

1. **Global Execution Context (GEC)**
    - This is the **default context** where your code starts execution.
    - It represents the [global scope](https://www.taqtiq.tech/insights/javascript-understanding-variables-and-scope#global-scope) in JavaScript.
    - It creates a [global object](https://developer.mozilla.org/en-US/docs/Glossary/Global_object) that is [`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) in the browser and [`global`](https://nodejs.org/api/globals.html#globals_global) in Node.js

2. **Function Execution Context (FEC)**
    - This is **created whenever a function is invoked.**
    - Each function gets its own execution context to **manage its local variables, arguments and inner functions.**
    - The function execution context corresponds to a functions [local scope](https://www.taqtiq.tech/insights/javascript-understanding-variables-and-scope#local-scope--function-scope).
3. **[`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) Execution Context**
    - The [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) function **evaluates JavaScript code represented as a string and returns its completion value.** The source is parsed as a script.
    - Example:
```
// language: js
console.log(eval(&quot;2 + 2&quot;));
// Expected output: 4

console.log(eval(new String(&quot;2 + 2&quot;)));
// Expected output: 2 + 2

console.log(eval(&quot;2 + 2&quot;) === eval(&quot;4&quot;));
// Expected output: true

console.log(eval(&quot;2 + 2&quot;) === eval(new String(&quot;2 + 2&quot;)));
// Expected output: false
```  

- The execution context of [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) is unique because it **depends entirely on how it is called: Direct vs. Indirect.**

### Direct [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) (shares the caller&apos;s scope)
- A direct call happens when you use the identifier eval directly (e.g. `eval(&quot;...&quot;)`).
- It executes inside the **current execution context** (the function or global scope where it was called) and has **full access to local variables, parameters, and [closures](https://www.taqtiq.tech/insights/javascript-understanding-variables-and-scope#what-are-closures).**
- If the code containing [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) is in [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) (or the evaluated string starts with &quot;use strict&quot;), **any variables declared inside [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) stay scoped inside the [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) call and do not leak into the outer function.**
- In [non-strict mode](https://developer.mozilla.org/en-US/docs/Glossary/Sloppy_mode), var declarations **leak into the surrounding function scope.**
```
// language: js
function testScope() {
  let localSecret = &quot;secret42&quot;;
  
  // Direct eval shares the lexical environment
  let result = eval(&quot;localSecret + &apos; evaluated&apos;&quot;);
  console.log(result); // Output: secret42 evaluated
}
testScope();
```

### Indirect [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) (uses [global scope](https://www.taqtiq.tech/insights/javascript-understanding-variables-and-scope#global-scope))
- An indirect call happens when eval is **referenced or called through something other than a direct property lookup** on the global object or direct identifier.
- Common examples include invoking it **via an aliased variable**, **via a member access or other expression**, or through the **optional chaining** [`?.`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) operator.

```
// language: js
// Direct call
eval(&quot;x + y&quot;);

// Indirect call using the comma operator to return eval
(0, eval)(&quot;x + y&quot;);

// Indirect call through optional chaining
eval?.(&quot;x + y&quot;);

// Indirect call using a variable to store and return eval
const myEval = eval;
myEval(&quot;x + y&quot;);

// Indirect call through member access
const obj = { eval };
obj.eval(&quot;x + y&quot;);
```
- **Indirect calls always execute in the global scope**. It cannot see local variables or parameters of the function it was called from.

### Why should you avoid using [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval)?
- **Security issues**. If any part of the string passed to [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) comes from a user input, the **user can execute malicious code in your application.**
- **Performance issues.** Because [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval)  can introduce entirely new variables or change code shapes at runtime, **engines have to disable many optimisations for code containing direct [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval).**
- **Maintainability and debugging issues.** Code inside strings **is opaque to [linters](https://www.w3schools.com/nodejs/nodejs_linting_formatting.asp), syntax highlighters and [minifiers](https://developer.mozilla.org/en-US/docs/Glossary/Minification).**

After having learnt about execution contexts, the **next part of grasping how JavaScript code runs** involves understanding how JavaScript **manages contexts with the call stack.**

## What is the call stack?

JavaScript uses a [&quot;Last In, First Out&quot; (LIFO)](https://www.geeksforgeeks.org/dsa/lifo-last-in-first-out-approach-in-programming/) data structure to manage the call stack.

### What is [&quot;Last In, First Out&quot; (LIFO)](https://www.geeksforgeeks.org/dsa/lifo-last-in-first-out-approach-in-programming/)?
- [&quot;Last In, First Out&quot; (LIFO)](https://www.geeksforgeeks.org/dsa/lifo-last-in-first-out-approach-in-programming/) is a **method for handling data structures** where the **first element is processed last** and the **last element is processed first.**
- An good example of this would be a stack (relevant - [stacks](https://www.geeksforgeeks.org/dsa/stack-data-structure/)) of books. 
- The **first book** to be placed on the stack will be the **last to be removed** if we only remove books from the top.

![Last-In-First-Out](/api/storage/kg2014779e95m5nqpv27cpr6s18gz56p)

### How does the call stack work in JavaScript?
- When JavaScript code begins running, it starts by pushing the Global Execution Context onto the stack.
- This sets up the global environment for your top-level code.
- As the program progresses, the engine handles pushing new Function Execution Contexts as functions are called.
- Each invoked function gets its own context added to the top of the stack.   
- The JavaScript engine executes what is currently at the top of the stack.
- It handles popping context off the stack when a function reaches a [`return`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return) or ends, returning control to the previous context.

![JavaScript Call Stack](/api/storage/kg2cmdb5y0wtj1t3tdxejxf9n98gzfhx)

![JavaScript Call Stack 2](/api/storage/kg20a3kmv76v9v8by6gnfezx9d8gzhey)

### Stack overflows
- If too many execution contexts accumulate without resolving, it can lead to a [stack overflow](https://docs.weblutions.com/spaces/knowledgebase/stack-overflow-errors) when the stack runs out of memory.

## What is the [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) keyword?

Now that we have covered what the call stack is, we can move on to understanding the [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) keyword in JavaScript.

- A good way to think of [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) is as a dynamic reference pronoun - similar to words like &quot;he&quot;, &quot;she&quot; or &quot;it&quot; in English.
- That is to say, who or what the pronoun refers to depends entirely on the context of the conversation.
- In JavaScript, [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) refers to the **object that is currently executing the current function.**

JavaScript determines the value of [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) based on four binding rules.

### Rule 1: Default binding
- When invoked as a standalone function (not attached to an object: `func()`), [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) typically refers to the global object (in [non-strict](https://developer.mozilla.org/en-US/docs/Glossary/Sloppy_mode) mode) or [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) (in [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode)).

```
// language: js
&quot;use strict&quot;;

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

showThis(); // Output: undefined (in strict mode)
```

### Rule 2: Implicit binding
- When a regular function is invoked as a method of an object (`obj.method()`), this points to that object.

```
// language: js
const user = {
  name: &quot;Alice&quot;,
  greet() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

user.greet(); // Output: &quot;Hello, my name is Alice&quot;
```

- *Implicit loss:* If you extract a method from an object and assign it to a variable, it loses its value.

```
// language: js
const unboundGreet = user.greet;
unboundGreet(); // Output: &quot;Hello, my name is undefined&quot; (or throws an error in strict mode)
```

### Rule 3: Explicit binding
- In JavaScript, you can **manually force** a function to use a specific object as its [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this), **regardless of how or where it is called.**
- [`bind()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) can create a function whose this binding doesn&apos;t change. It does not invoke the function immediately, but instead creates a new function with [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) permanently bound to the argument passed in to it.

```
// language: js
const button = {
  text: &quot;Click me&quot;,
  click: function() {
    console.log(`Button text is: ${this.text}`);
  }
};

// If passed directly as a callback, &apos;this&apos; would be lost (pointing to global/undefined)
// setTimeout(button.click, 1000); 

// Using bind fixes the context:
const boundClick = button.click.bind(button);
setTimeout(boundClick, 1000); 
// Output after 1 second: &quot;Button text is: Click me&quot;
```

- [`apply()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) on the other hand *does* execute immediately. It binds the method passed to its [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) and takes an array as an argument.

```
// language: js
const numbers = [5, 6, 2, 3, 7];

// Math.max doesn&apos;t accept arrays directly, but we can use apply
const max = Math.max.apply(null, numbers);
console.log(max); // Output: 7

// Alternatively, with an object context:
console.log(person.fullName.apply(person1, [&quot;New York&quot;, &quot;USA&quot;]));
// Output: &quot;John Doe from New York, USA&quot;
```

- [`call`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) behaves very similarly to [`apply()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply), but instead takes arguments listed consecutively instead of an array.

```
// language: js
const person = {
  fullName: function(city, country) {
    return `${this.firstName} ${this.lastName} from ${city}, ${country}`;
  }
};

const person1 = { firstName: &quot;John&quot;, lastName: &quot;Doe&quot; };

// Arguments are passed individually separated by commas
console.log(person.fullName.call(person1, &quot;New York&quot;, &quot;USA&quot;));
// Output: &quot;John Doe from New York, USA&quot;
```

| Feature | [`call`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) | [`apply()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) | [`bind()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) |
| :--- | :--- | :--- | :--- |
| **Execution** | Executes immediately | Executes immediately | Returns a **new function** (does not execute immediately) |
| **Argument Passing** | Passed individually as a comma-separated list (`arg1, arg2`) | Passed as a **single array** (`[arg1, arg2]`) | Passed individually (at binding time or execution time) |
| **Use Case** | Borrowing methods with known arguments | Borrowing methods when arguments are in an array | Creating a permanently bound function (e.g., for callbacks or event handlers) |


### Rule 4: [`new`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new) binding
- When you invoke a function using the [`new`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new) keyword, JavaScript treats it as a constructor.

When [`new`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new) is used, JavaScript will do the following things:

1. Create a new, empty object.
2. Link the new object&apos;s [prototype](https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/Advanced_JavaScript_objects/Object_prototypes) (`[[prototype]]`) to the constructor functions [prototype](https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/Advanced_JavaScript_objects/Object_prototypes).
3. Binds the [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) to point to that newly created object.
4. Returns the object.

```
// language: js
function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

const car1 = new Car(&quot;Eagle&quot;, &quot;Talon TSi&quot;, 1993);

console.log(car1.make);
// Expected output: &quot;Eagle&quot;
```

## How do [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) handle [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)?
- [Arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) differ in their handling of [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this).
- They inherit [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) from their parent scope at the time they are defined.
- You cannot change an arrow function&apos;s this using [`call`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call), [`apply()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply), or [`bind()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).

```
// language: js
const group = {
  title: &quot;Engineering&quot;,
  members: [&quot;Alice&quot;, &quot;Bob&quot;],
  
  showMembers() {
    // Regular function here would lose &apos;this&apos; inside the callback,
    // but arrow function lexically inherits &apos;this&apos; from showMembers()
    this.members.forEach(member =&gt; {
      console.log(`${member} is in ${this.title}`);
    });
  }
};

group.showMembers(); 
// Output: 
// Alice is in Engineering
// Bob is in Engineering
```</content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript: Understanding Variables and Scope]]></title>
            <description><![CDATA[An in-depth look at variables and scope in JavaScript, covering hoisting, closures and the 'temporal dead zone'.]]></description>
            <link>https://www.taqtiq.tech/blog/javascript-understanding-variables-and-scope</link>
            <guid isPermaLink="false">j978y3q9fvy5qa3j8r5xhtyaj58g45t6</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[tutorials]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 01:45:07 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/ed302619-7070-45cf-baf3-98e23ab08991" length="0" type="audio/mpeg"/>
            <content:encoded>## What are variables?

- In programming, variables are simply **containers used to store data.**
 
- You can think of a variable as a **box with a label**:
    - The label corresponds to the variables name (e.g. `username`, `num1`, `isLoggedIn`, etc.).
    - The contents inside the box are the values that we are storing (e.g. `&quot;user1&quot;`, `100`, `true`).

![Variables Box Analogy](/api/storage/kg2a0gfte8p6saw2zpgkph2sgd8gy2rr)

- Working with variables involves three key concepts:
    1. **Declaration (Creating the box)**. This is where we instruct the computer to create a variable and give it a name.
    2. **Initialisation / Assignment (Putting something inside the box)**. This is where we give the variable we declared a value. We do this with the assignment (`=`) operator.
    3. **Retrieval / Usage (Looking inside the box)**. This is where we access the contents of the variable (the value we stored) to use it in our code.
 
**Here is a quick example of variables in JavaScript:**

```
// language: js

// Declaring a variable named &apos;score&apos; and assigning it the value 50
let score = 50;

// Using the variable
console.log(score); // Output: 50

// Change the value later on
score = 75;
console.log(score); // Output: 75

```

### Why do we need variables?

- **To store data.** Throughout the lifecycle of a program, data will need to be tracked so it can be used later on.
- **To make code that is reusable**. Variables allow us to generalise our code so that it works no matter what values are assigned to it (e.g. we can write formulas with variables - `totalPrice = itemPrice * taxRate`).
- **To handle data that changes.** Over the course of a programs [runtime](https://en.wikipedia.org/wiki/Execution_(computing)) things will change. Variables allow us to track and update that changing state.
- **To improve code readability and make code easier to maintain.** 

### What are &apos;data types&apos;?
- Data can come in different forms. **In other words, there are different &apos;types&apos; of data.**
- **Some common data types in JavaScript include:**
    - [**Strings**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String). Text which is wrapped in quotes (e.g. `let name = &quot;Alex&quot;;`).
    - [**Numbers.**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) Integers or decimals (e.g. `let temperature = 72.5;`).
    - [**Booleans.**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean) True or false values (e.g. `let isLoggedIn = true;`)
    - [Arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)/[Objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object). Lists or complex collections of data.

![Data Types](/api/storage/kg2eajvnq848ynkv22xz427tgn8gy2wp)

## What is &apos;scope&apos;?

&gt; Scope is the current context of execution in which values and expressions are &quot;visible&quot; or can be referenced. If a variable or expression is not in the current scope, it will not be available for use.

[&apos;Scope&apos; MDN Documentation](https://developer.mozilla.org/en-US/docs/Glossary/Scope)

- To put it more simply, scope determines where in your code a variable can be seen and used.

![Scope Hierarchy](/api/storage/kg2dkse6sy85d8re885mr8sa7n8gy3e0)

### Why does scope matter?

- **For security and encapsulation.** Scope prevents unintended parts of the codebase from accessing or [mutating](https://developer.mozilla.org/en-US/docs/Glossary/Mutable) sensitive data.
- **For [namespace](https://developer.mozilla.org/en-US/docs/Glossary/Namespace) management.** Scope allows you to reuse variable names in different parts of your code without conflicts.
- **For [garbage collection](https://developer.mozilla.org/en-US/docs/Glossary/Garbage_collection).** Allows the computer to free up memory once variables fall out of scope.

### What are the different types of scope?

### [Global scope](https://developer.mozilla.org/en-US/docs/Glossary/Global_scope)
- The global scope is **any variables declared outside of any function or block.**
- Globally scoped variables can be **accessed from anywhere in the entire program.**
- **Global variables should be used sparingly as they can often lead to bugs** as their values can be changed from anywhere in the program.

```
// language: js
let carName = &quot;Volvo&quot;;
// code here can use carName

function myFunction() {
// code here can also use carName
}
```

### [Local Scope / Function Scope](https://developer.mozilla.org/en-US/docs/Glossary/Local_scope)
- The local scope is **any variable declared within a specific function or block of code** (such as inside an `if` statement or `for` loop dependant on the language).
- Locally scoped variables can **only be accessed from within that specific function or block.** 
- They are usually **cleared from memory once the function finishes running.**

```
// language: js
function greet() {
  let message = &quot;Hello from inside the function!&quot;;
  console.log(message); // Works fine
}

greet();

// Trying to access it outside the function throws an error:
console.log(message); 
// ReferenceError: message is not defined
```

### [Block Scope](https://www.w3schools.com/js/js_scope.asp)
- The block scope encompasses **any variables that are declared inside curly braces (`{}`).**
- **Variables declared with [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) and [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) in JavaScript are block scoped.**
- Example:

```
// language: js
{
  let x = 2;
}
// x can not be used here 
```

### What is [&apos;Lexical Scope&apos;](https://www.freecodecamp.org/news/javascript-lexical-scope-tutorial/) in JavaScript?
- Lexical scope (or static scope) means that **variable accessibility is determined entirely by where the variables and blocks are physically written in your source code**.
- JavaScript uses the ***physical* structure of your code to decide which variables are available. Where you call a function doesn&apos;t matter; where you *write* it does.**
- Because scope is lexically determined, **you can look at a piece of code and trace with absolute certainty which variables a function has access to just by reading the nesting structure.**
- Example:

```
// language: js
const globalVar = &quot;I am global&quot;;

function outer() {
  const outerVar = &quot;I am in outer&quot;;

  function inner() {
    const innerVar = &quot;I am in inner&quot;;
    // inner can see globalVar, outerVar, and innerVar
    console.log(globalVar, outerVar, innerVar);
  }
  
  inner();
}
```

### The [scope chain](https://www.freecodecamp.org/news/deep-dive-into-scope-chains-and-closures-21ee18b71dd9/)
- When looking for a variable, JavaScript always **starts looking in the innermost current scope and moves outwards from there.**
- If a variable isn&apos;t found in the current scope, **it steps up to the parent scope**, then the parent of the parent scope, and so on.
- As soon as JavaScript finds the variable, **it stops searching and uses it.**
- If it reaches the global scope and still can&apos;t find it, it either throws a [`ReferenceError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError) or creates a global variable (in non-strict mode).

## How do you declare variables in JavaScript?

- JavaScript provides three keywords for variable declaration. Here is a quick overview of each:

| Feature | [`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) (Legacy / ES5) | [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) (Modern / ES6) | [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) (Modern / ES6) |
| :--- | :--- | :--- | :--- |
| **Re-declaration** | Allowed in the same scope. | Not allowed in the same scope. | Not allowed. |
| **Re-assignment** | Allowed. | Allowed. | Not allowed (Must be assigned a value when declared). |
| **Initialisation** | Optional (defaults to [`undefined`](https://developer.mozilla.org/en-US/docs/Glossary/Undefined)). | Optional (defaults to [`undefined`](https://developer.mozilla.org/en-US/docs/Glossary/Undefined)). | Required upon declaration. |

### [`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) keyword
- [`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) is the legacy method of declaring variables.
- Since the introduction of [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) and [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) in [ES6 (ECMAScript 2015)](https://www.w3schools.com/js/js_es6.asp), `var` **is generally considered to be outdated so its usage should be avoided.**
- [`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) **is function scoped**.
- Variables defined with [`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) **can be redeclared in the same scope**.
- Variables defined with [`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) **can be reassigned**.
- Variables defined with [`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) **do not *have* to be initialised**. Their value will default to [`undefined`](https://developer.mozilla.org/en-US/docs/Glossary/Undefined).

```
// language: js
// 1. Basic declaration and assignment
var name = &quot;Alice&quot;;
console.log(name); // Output: Alice

// 2. Variables declared with var can be reassigned
name = &quot;Bob&quot;;
console.log(name); // Output: Bob

// 3. Variables declared with var can be redeclared in the same scope
var name = &quot;Charlie&quot;;
console.log(name); // Output: Charlie

// 4. Function scope example
function testVar() {
  var score = 100;
  if (true) {
    var score = 200; // Same variable! var is function scoped, not block-scoped
    console.log(score); // Output: 200
  }
  console.log(score); // Output: 200 (the inner change affected the outer one)
}
testVar();
```

### [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) keyword
- [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) is the **modern method for declaring variables** in JavaScript.
- [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) was introduced in [ES6 (ECMAScript 2015)](https://www.w3schools.com/js/js_es6.asp).
- [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) is **block scoped**, meaning variables declared with [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) are **only accessible within the nearest enclosing block (`{}`) in which they are defined**.
- Variables defined with [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) **cannot be redeclared within the same scope.**
- Variables defined with [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) **can be reassigned.**
- Variables defined with [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) **do not *have* to be initialised**. Their value will default to [`undefined`](https://developer.mozilla.org/en-US/docs/Glossary/Undefined).

```
// language: js
// 1. Basic declaration and assignment
let name = &quot;Alice&quot;;
console.log(name); // Output: Alice

// 2. Variables declared with let can be reassigned
name = &quot;Bob&quot;;
console.log(name); // Output: Bob

// 3. Redeclaration in the same scope is not allowed (throws a SyntaxError)
// let name = &quot;Charlie&quot;; // SyntaxError: Identifier &apos;name&apos; has already been declared

// 4. Block scope example (unlike var)
function testLet() {
  let score = 100;
  if (true) {
    let score = 200; // A completely separate variable! let is block scoped
    console.log(score); // Output: 200
  }
  console.log(score); // Output: 100 (the outer score remains untouched)
}
testLet();
```

### [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) keyword
- The [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) keyword is **JavaScript&apos;s method for declaring [constants](https://www.w3schools.com/programming/prog_constants.php).**
- [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) was introduced in [ES6 (ECMAScript 2015)](https://www.w3schools.com/js/js_es6.asp).
- [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) is **block scoped**, meaning variables declared with [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) are **only accessible within the nearest enclosing block (`{}`) in which they are defined**.
- Variables defined with [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) **cannot be redeclared.**
- Variables defined with [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) **cannot be reassigned.**
- For objects and arrays declared with [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const), the reference is [immutable](https://developer.mozilla.org/en-US/docs/Glossary/Immutable), **but the internal contents/properties can still be modified.**

```
// language: js
// 1. Basic declaration and assignment (must be initialised immediately)
const name = &quot;Alice&quot;;
console.log(name); // Output: Alice

// 2. Re-assignment is not allowed (throws a TypeError)
// name = &quot;Bob&quot;; // TypeError: Assignment to constant variable.

// 3. Re-declaration in the same scope is not allowed (throws a SyntaxError)
// const name = &quot;Charlie&quot;; // SyntaxError: Identifier &apos;name&apos; has already been declared

// 4. Block scope example 
function testConst() {
  const score = 100;
  if (true) {
    const score = 200; // Completely separate variable! const is block-scoped
    console.log(score); // Output: 200
  }
  console.log(score); // Output: 100
}
testConst();

// 5. Important: const protects the binding, not the value (mutability)
const user = { name: &quot;Alice&quot; };
user.name = &quot;Bob&quot;; // Allowed! We are mutating the object property, not reassigning the variable.
console.log(user.name); // Output: Bob
// user = { name: &quot;Charlie&quot; }; // TypeError: Assignment to constant variable.
```

## What is hoisting in JavaScript?

&gt; JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables, classes, or imports to the top of their scope, prior to execution of the code.

[&apos;Hoisting&apos; MDN Documentation](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting)

- To put it simply, hoisting is a **mechanism in JavaScript where variable and function declarations are moved (or &quot;hoisted&quot;) to the top of their containing scope.**
- This **happens during the compilation phase, *before* the code is executed line by line.**
- JavaScript **only hoists declarations, not initialisations.**
- This means that the **variable names are stored in memory during compilation**, but their **assigned values remain where they are in the code** until execution reaches them.

![Variable Hoisting](/api/storage/kg2dgtqb9dtyg5d6n3mbr3r2ss8gzes5)

### How does hoisting behave?
- Hoisting behaves differently depending on how the variable is declared (with [`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var), [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) or [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const)).

### [`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) hoisting
- Variables declared with [`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) are **hoisted to the top of their scope.**
- They are initialised with a value of [`undefined`](https://developer.mozilla.org/en-US/docs/Glossary/Undefined).
- This means you can **reference the variable before it is declared in your code** without throwing a syntax error, but its value will be **undefined until the assignment line is reached.**
- Example:

```
// language: js
console.log(name); // Output: undefined (not a ReferenceError!)
var name = &quot;Alice&quot;;
console.log(name); // Output: Alice
```

### [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) and [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) hoisting
- Variables declared with [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) and [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) **are also hoisted.**
- **But they are *not* initialised with** [`undefined`](https://developer.mozilla.org/en-US/docs/Glossary/Undefined). 
- Instead, entering the scope places them in a [Temporal Dead Zone (TDZ)](https://www.freecodecamp.org/news/javascript-temporal-dead-zone-and-hoisting-explained/) from the start of the block until the declaration line is evaluated.
- Attempting to access them during this window throws a [`ReferenceError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError).
- Example:

```
// language: js
console.log(age); // Throws ReferenceError: Cannot access &apos;age&apos; before initialisation
 let age = 30;
```

### What exactly is the [Temporal Dead Zone (TDZ)](https://www.freecodecamp.org/news/javascript-temporal-dead-zone-and-hoisting-explained/)?

- The [Temporal Dead Zone (TDZ)](https://www.freecodecamp.org/news/javascript-temporal-dead-zone-and-hoisting-explained/) is the **span time from the start of a block or scope until a [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) or [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const)  variable is fully declared and initialised.**
- During this zone, the **variable *does* exist in memory** (meaning it has been hoisted), but the JavaScript engine **does not allow you to access it.**

![Temporal Dead Zone](/api/storage/kg2f20reqy7wfn995hbkkndky18gyjc1)

### Why does the [Temporal Dead Zone (TDZ)](https://www.freecodecamp.org/news/javascript-temporal-dead-zone-and-hoisting-explained/) exist?
- The [Temporal Dead Zone (TDZ)](https://www.freecodecamp.org/news/javascript-temporal-dead-zone-and-hoisting-explained/) was introduced in [ES6 (ECMAScript 2015)](https://www.w3schools.com/js/js_es6.asp) with the purpose of addressing the design flaws and silent failures baked into [`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) hoisting.
- Before [ES6 (ECMAScript 2015)](https://www.w3schools.com/js/js_es6.asp), JavaScript only had function scope ([`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var)), which led to **messy variable leaking, confusing hoisting behaviour**, and **accidental global pollution**.
- Example:

```
// language: js
var count = 10;
function process() {
  console.log(count); // Output: undefined (instead of throwing an error!)
  var count = count + 1; // Evaluates undefined + 1 -&gt; NaN
}
process();
```
- **This confusing behaviour still persists with [`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var), which is why it should be used sparingly.**

## What are &apos;Closures&apos;?

&gt; A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives a function access to its outer scope. In JavaScript, closures are created every time a function is created, at function creation time.

[&apos;Closures&apos; MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures)

- A closure is **created whenever a function is bundled (enclosed) with references to its surrounding state (its lexical environment).**
- A closure gives an inner function **access to an outer function&apos;s scope, even after the outer function has finished executing** and returned.
- Normally, when a function finishes running, its local variables are cleared from memory by the garbage collector.
- However, if an inner function retains a reference to those outer variables (often by being returned or passed elsewhere), **those variables stay alive in memory.**
- Example - Closures are frequently used to create private variables that cannot be modified directly from the outside:

```
// language: js
function createCounter() {
  let count = 0; // This variable is private

  return {
    increment: function() {
      count++;
      return count;
    },
    decrement: function() {
      count--;
      return count;
    },
    getCount: function() {
      return count;
    }
  };
}

const myCounter = createCounter();
console.log(myCounter.increment()); // 1
console.log(myCounter.increment()); // 2
console.log(myCounter.getCount());  // 2
// console.log(count); // ReferenceError: count is not defined
```
</content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is the Document Object Model in Web Applications?]]></title>
            <description><![CDATA[A summary of what the DOM is, why it exists and how it works, a quick history of the DOM and a dive into how you can manipulate the DOM.]]></description>
            <link>https://www.taqtiq.tech/blog/what-is-the-document-object-model-in-web-applications</link>
            <guid isPermaLink="false">j97c2dzbktjf92s6cd3pxcjf9h8ftq2z</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[tutorials]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 01:54:57 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/c003c78b-fac2-4b14-a447-ecc756c98053" length="0" type="audio/mpeg"/>
            <content:encoded>## What is the DOM?

&gt; The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; that way, programming languages can interact with the page.

[MDN Document Object Model](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model#concepts_and_usage)

- In simple terms, the **DOM is an interactive, live map of a webpage that allows JavaScript to change text, styles or structure in real time.**
- The DOM turns **raw HTML code into a tree of interactive objects that JavaScript can manipulate**.
- The DOM acts as a **bridge between raw, static HTML and dynamic programming languages** like JavaScript.

![Static HTML to DOM](/api/storage/kg2aats4g78bjr0h747mkrcgv98gz2sd)

## Why does the DOM exist? (a quick history of the DOM)

- The DOM exists so that JavaScript can alter page structure, styles and update content without refreshing. Essentially, it allows web pages to be **dynamic**.
- It wasn&apos;t always like this though.
- **From 1989 to 1995 the web existed completely without the DOM.**
- During this era, websites were purely static HTML documents without dynamic changes or interactive elements.

![Amazon](/api/storage/kg243313a09a6v0fak5s89mv3s8fzwet)

### 1995
1. In 1995, [Netscape](https://en.wikipedia.org/wiki/Netscape) introduced JavaScript which included a basic set of object bindings like `document.forms` and `document.images` to allow scripts to interact with page elements. This became known as **DOM level 0.**
### 1996 - 1998
2. Between 1996 and 1998 [Netscape](https://en.wikipedia.org/wiki/Netscape) and Microsoft fought over control of the web. Both companies introduced features to make web pages more interactive, but both built completely incompatible models:
    - Netscape 4 introduced the `&lt;layer&gt;` element and `document.layers`.
    - Internet Explorer 4 introduced `document.all`.
### 1998 - 2000
3. In 1998, the [World Wide Web Consortium (W3C)](https://www.w3.org/) formed a dedicated DOM Working Group to standardise the rules.
    - **DOM Level 1 (1998):** Defined the first official, platform-neutral specification for representing documents as a tree of nodes. It introduced core selection and node manipulation methods like [`getElementById`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById), [`appendChild`](https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild), and [`createElement`](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement).
    - **DOM Level 2 (2000):** Introduced crucial modern primitives, stylesheet manipulation, and the standardised event model ([`addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) and [`removeEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener)).

### 2006
 4. Even with standards, browsers had bugs and inconsistencies. In 2006, [jQuery](https://jquery.com/) was released, which hid those inconsistencies behind a universal wrapper.

### 2011 - Present
 5. In 2011, browsers finally agreed to follow identical standards. Today, the DOM is considered to be a **&quot;living standard&quot;**, meaning that it is updated continuously to support modern web apps and components.

## How exactly does the DOM work?
### How the browser builds the DOM
### Step 1: Bytes to characters
- When a web server responds to a request, the HTML file is sent across the network as raw binary data (a stream of `0`s and `1`s).
1. **Byte Stream:** The browser receives chunks of bytes over HTTP.
2. **Character encoding:** The browser looks at the HTTP response header `Content-Type: text/html; charset=UTF-8` (or the `&lt;meta charset=&quot;UTF-8&quot;`&gt; tag) to convert the bytes into characters (text strings like `&lt;html&gt;`, `&lt;body&gt;`, `&lt;p&gt;`)

![Bytes to Characters](/api/storage/kg232j3v91jqnhw3z0qk9ej3ds8gyasb)

### Step 2: Character Stream to Tokens ([Tokenisation](https://html.spec.whatwg.org/multipage/parsing.html#tokenization))
- The character stream is then fed into a **tokeniser**. The HTML specification defines a [state machine](https://developer.mozilla.org/en-US/docs/Glossary/State_machine) that reads characters one by one to produce discrete structural tokens:
    - **StartTag:** e. g. `StartTag: html`, `StartTag: body`, `StartTag: p`
    - **EndTag:** e. g. `EndTag: p`, `EndTag: body`
    - **Tag Attributes:** e. g. `class=&quot;container&quot;`, `id=&quot;main&quot;`
    - **Plain Text Contents:** e. g. `&quot;My Document&quot;`.

![Tokeniser](/api/storage/kg2c9k4wtenvy3x4pnz2wmwwj18gzz70)

### Step 3: Tokens to Nodes
- A tree construction algorithm processes the tokens as they are emitted from the tokeniser to create C++ object instances representing DOM nodes:
   - An Element object for HTML elements (e.g. [`HTMLParagraphElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLParagraphElement), [`HTMLDivElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDivElement)).
   - A [`Text`](https://developer.mozilla.org/en-US/docs/Web/API/Text) object for raw text inside elements.
   - A [`Comment`](https://developer.mozilla.org/en-US/docs/Web/API/Comment) object for HTML comments.
- Each Node object contains built-in methods, event listener queues, pointers to parent/child nodes, and custom attributes.

![Tokens to Nodes](/api/storage/kg2cttzdeyt8zqc8mq56rw0rqh8gyrzw)

### Step 4: Tree construction
- HTML parsing uses a **Tree Construction State Machine** powered by an [Open Elements Stack](https://web.dev/articles/howbrowserswork#html_parser) to construct the tree, even when the HTML code contains errors.

![DOM Tree](/api/storage/kg2edya5dq8xqb084dth9j83918gzcfw)

## How can you manipulate the DOM?
### Selecting elements
- **Before modifying a DOM element, you need to select it first.**
- There are three main ways to identify an element. Its [`id`](https://developer.mozilla.org/en-US/docs/Web/API/Element/id), [`className`](https://developer.mozilla.org/en-US/docs/Web/API/Element/className) and [`tagName`](https://developer.mozilla.org/en-US/docs/Web/API/Element/tagName).
- The [`document`](https://developer.mozilla.org/en-US/docs/Web/API/Document) interface provides three methods to select by these identifiers:
    1. [`document.getElementById()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)
    2. [`document.getElementsByClassName()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName)
    3. [`document.getElementsByTagName()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName)
 ```
// language: js
const containerDiv = document.getElementById(&quot;container&quot;);
// containerDiv is an HTMLDivElement

const profileDivs = document.getElementsByClassName(&quot;profile&quot;);
// profileDivs is an HTMLCollection containing an HTMLDivElement

const profileDivs2 = document.getElementsByTagName(&quot;div&quot;);
// profileDivs2 is an HTMLCollection containing both HTMLDivElements
```

- You can **also use CSS selectors to select elements.** Two methods are available:
    1. [`document.querySelector()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector)
    2. [`document.querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll)
 
```
// language: js
const el = document.querySelector(&quot;#main, #basic, #exclamation&quot;);

const special = document.querySelectorAll(&quot;p.warning, p.note&quot;);
```

### Modifying content and attributes
- Once a node has been selected, you can begin modifying its properties and attributes. **The attributes that can be modified will be defined on the interface itself** (e. g. [`HTMLTitleElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTitleElement)).

```
// language: js
// Select the HTML &lt;title&gt; element directly by tag name
const titleElement = document.querySelector(&apos;title&apos;);

// Update its content using the HTMLTitleElement `.text` property
titleElement.text = &apos;New Page Title&apos;;

// The same thing can actually be done with this shortcut:
document.title = &apos;New Page Title&apos;;
```
- Another example, modifying image properties:
```
// language: js
const image = document.querySelector(&apos;img&apos;);
image.setAttribute(&apos;src&apos;, &apos;new-image.jpg&apos;);
image.alt = &apos;Updated profile picture&apos;;
```

### Modifying styles and CSS classes
- You can also modify the CSS styles attached to an element.
```
// language: js
const box = document.querySelector(&apos;.box&apos;);

// Direct inline styling
box.style.backgroundColor = &apos;royalblue&apos;;
box.style.padding = &apos;20px&apos;;

// Class manipulation
box.classList.add(&apos;active&apos;);
box.classList.remove(&apos;hidden&apos;);
box.classList.toggle(&apos;highlight&apos;);
```

### Creating, appending and removing elements
#### Creating
- You can dynamically add nodes to the DOM.
- Calling [`document.createElement(tagName)`](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement) instantiates an unattached node in browser memory.
- **Until you insert it into an active DOM tree, it remains invisible on the rendered page.**
```
// language: js
// Instantiates an HTMLDivElement node in memory
const card = document.createElement(&apos;div&apos;);

// Configure properties on the unattached node
card.className = &apos;card-item&apos;;
card.textContent = &apos;Card title&apos;;
```
#### Appending
- The node will need to be appended to an existing parent node on the DOM tree.
- There are two main APIs for insertion:
    1. [`appendChild()`](https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild) - Accepts a single Node object and returns the inserted node.
    2. [`append()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/append) - Inserts multiple nodes at once and directly takes plain text strings.
```
// language: js
const container = document.querySelector(&apos;.container&apos;);

// Modern Element.append() - handles multiple items or raw strings
container.append(card, &apos;Additional string node&apos;);

// Classic Node.appendChild() - handles a single node
container.appendChild(card);
``` 
#### Removing
- You can remove nodes from the DOM with the modern [`element.remove()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/remove) method.
- This directly removes the element from its parent node.
- There is also the legacy [`parentNode.removeChild()`](https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild) method where you must call the method on the *parent* node and pass the target child node.

```
// language: js
const element = document.querySelector(&apos;.card-item&apos;);

// Modern direct removal
element.remove();

// Legacy parent-based removal
element.parentNode.removeChild(element);
```

#### Handling events
- You can tap into user events (e. g. mouse clicks, key presses, scroll events, etc.) by attaching event listeners.
- This allows you to trigger DOM changes based on user actions.
- [`addEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) is the standard way of doing this.

```
// language: js
const button = document.querySelector(&apos;#submit-btn&apos;);

button.addEventListener(&apos;click&apos;, (event) =&gt; {
  event.preventDefault();
  alert(&apos;Button clicked!&apos;);
});
```</content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js: What Is Hydration?]]></title>
            <description><![CDATA[An in-depth look at what hydration is in the context of Next.js, with descriptions on how to address common causes of hydration mismatch errors.]]></description>
            <link>https://www.taqtiq.tech/blog/nextjs-what-is-hydration</link>
            <guid isPermaLink="false">j9798hj7s5xqc11qadxhrq5v118fmjeq</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[tutorials]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 01:41:04 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/c31c777b-742f-47b5-9ff1-86c9c576bbc6" length="0" type="audio/mpeg"/>
            <content:encoded>## Why does hydration exist?
- Pure [Client-Side Rendering (CSR)](https://nextjs.org/docs/pages/building-your-application/rendering/client-side-rendering) leads to users staring at a blank screen while JavaScript downloads and executes in the clients browser.
- [Server-Side Rendering (SSR)](https://nextjs.org/docs/pages/building-your-application/rendering/server-side-rendering) fixes this by sending pre-rendered HTML/CSS instantly from the server, giving users an improved [First Contentful Paint (FCP)](https://web.dev/articles/fcp).

- This comes with an important caveat though: [HTML is inert](https://www.merriam-webster.com/dictionary/inert). Since it is rendered on the server, it cannot tap into browser events (buttons can&apos;t handle [`onClick`](https://react.dev/learn/responding-to-events), forms aren&apos;t connected to state and so on).

![Client-Side Rendering VS Server-Side Rendering](/api/storage/kg22fpmr78wf2mt52qnajtr2g98gyaxm)

- To address this caveat, we use **hydration**.

## What is hydration?

&gt; React&apos;s process of attaching event handlers to the DOM to make server-rendered static HTML interactive. During hydration, React reconciles the server-rendered markup with the client-side JavaScript.

[Next.js Glossary](https://nextjs.org/docs/app/glossary#hydration)

- Effectively, the idea is that we can make the page render instantly and at the same time maintain client side interactivity by rendering the static shell of the page first and then adding the client side features.

![Hydration](/api/storage/kg26472q9xxqybx0djv3mt8bwx8gz969)

## Why is it called hydration?

- The commonly used analogy is of a sponge that is initially dry and is then soaked in water. 

![Sponge Analogy](/api/storage/kg2542sa92n2a5r7jx5w12wc3h8gz4et)

## How does hydration work under the hood?
1. **Server phase:** React executes components on the server using methods like:
    - [`renderToString`](https://react.dev/reference/react-dom/server/renderToString) *(traditional / synchronous)*
    - [`renderToReadableStream`](https://react.dev/reference/react-dom/server/renderToReadableStream) *(modern / streaming)*
2. **Parsing phase:** The browser parses the HTML and renders the visual layout immediately.
3. **Download phase:** The browser fetches the JavaScript bundle containing React and your component code.
4. **Reconciliation and attachment phase:** React executes in the browser, builds an in-memory Virtual DOM tree, matches (reconciles) those nodes with the real DOM nodes already on screen, and binds all event handlers without re-rendering the actual HTML elements.

## What are hydration mismatch errors?

&gt; While rendering your application, there was a difference between the React tree that was prerendered from the server and the React tree that was rendered during the first render in the browser (hydration).

[Next.js Hydration Errors](https://nextjs.org/docs/messages/react-hydration-error#why-this-error-occurred)
- To put it simply, a hydration mismatch error is a discrepancy between the HTML that was pre-rendered on the server and what React computed on the client.

![Hydration Mismatch Error](/api/storage/kg2417awn2hbf476rasvg0pkch8gy5n2)

## What causes hydration mismatch errors (common triggers)?
- **Browser-only APIs:** Accessing [`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window), [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage), or [`document`](https://developer.mozilla.org/en-US/docs/Web/API/Document) during the initial render.
- **Dynamic Data:** Rendering [`new Date()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date) or [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) during render, which produces different values on server vs. client.
- **Invalid HTML Nesting:** Browser auto-correcting illegal markup (e.g., placing a [`&lt;div&gt;`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/div) inside a [`&lt;p&gt;`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/p) tag), causing the client DOM to differ from the server HTML string.

## How do you fix hydration mismatch errors (common fixes)?

Resolving hydration mismatch errors comes down to one core principle - **ensure the initial client render produces the exact same HTML structure and text that was rendered on the server.**

1. **Shift Client-Side State into [`useEffect`](https://nextjs.org/docs/pages/building-your-application/data-fetching/client-side).**
    - As mentioned, trying to access browser only APIs on the initial render (such as [`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window), [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage), or [`document`](https://developer.mozilla.org/en-US/docs/Web/API/Document)) will cause a hydration mismatch.
    - To resolve it, you can initialise state with a default value, then update it inside [`useEffect`](https://nextjs.org/docs/pages/building-your-application/data-fetching/client-side).
    - This works because [`useEffect`](https://nextjs.org/docs/pages/building-your-application/data-fetching/client-side) runs only in the browser after the initial hydration process.
```
// language: ts
// title: ThemeToggle.tsx
&apos;use client&apos;;
import { useState, useEffect } from &apos;react&apos;;

export default function ThemeToggle() {
  const [theme, setTheme] = useState(&apos;light&apos;); // Matches server default

  useEffect(() =&gt; {
    // Runs ONLY on client after initial hydration completes
    const savedTheme = localStorage.getItem(&apos;theme&apos;);
    if (savedTheme) setTheme(savedTheme);
  }, []);

  return &lt;div&gt;Current theme: {theme}&lt;/div&gt;;
}
// language: js
// title: ThemeToggle.jsx
&apos;use client&apos;;
import { useState, useEffect } from &apos;react&apos;;

export default function ThemeToggle() {
  const [theme, setTheme] = useState(&apos;light&apos;); // Matches server default

  useEffect(() =&gt; {
    // Runs ONLY on client after initial hydration completes
    const savedTheme = localStorage.getItem(&apos;theme&apos;);
    if (savedTheme) setTheme(savedTheme);
  }, []);

  return &lt;div&gt;Current theme: {theme}&lt;/div&gt;;
}
```
2. **Handle non-deterministic data properly (dates, timestamps, random numbers).**
    - The server and client will evaluate non-deterministic data like dates ([`new Date()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date)) or random values ([`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random)) differently.
- There are two possible solutions for this:
    1. Compute timestamps on the server (in a server component) and pass the formatted string down as a prop.
    2. Keep the initial markup static and format the date on the client side inside a [`useEffect`](https://nextjs.org/docs/pages/building-your-application/data-fetching/client-side) or [`useSyncExternalStore`](https://react.dev/reference/react/useSyncExternalStore).
3. **Fix invalid HTML nesting.**
    - Browsers will autocorrect invalid HTML nesting before hydration.
    - For instance, if you nest a [`&lt;div&gt;`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/div) inside a [`&lt;p&gt;`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/p), the browser automatically splits the [`&lt;p&gt;`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/p) into two separate elements in the DOM tree, throwing off React&apos;s reconciliation.

```
// language: ts
// ❌ Invalid HTML: &lt;p&gt; cannot contain block elements like &lt;div&gt;
&lt;p&gt;
  &lt;div&gt;Some content&lt;/div&gt;
&lt;/p&gt;
// language: js
// ❌ Invalid HTML: &lt;p&gt; cannot contain block elements like &lt;div&gt;
&lt;p&gt;
  &lt;div&gt;Some content&lt;/div&gt;
&lt;/p&gt;
```
Use valid HTML structure instead:
```
// language: ts
// ✅ Valid HTML
&lt;div&gt;
  &lt;div&gt;Some content&lt;/div&gt;
&lt;/div&gt;
// language: js
// ✅ Valid HTML
&lt;div&gt;
  &lt;div&gt;Some content&lt;/div&gt;
&lt;/div&gt;
```
4. **Disable SSR for specific components.**
    - Sometimes a component will rely heavily on browser-only functionality.
    - In this case, you can **disable SSR** for that particular component which can resolve a hydration mismatch error.
```
// language: ts
import dynamic from &apos;next/dynamic&apos;
 
const NoSSR = dynamic(() =&gt; import(&apos;../components/no-ssr&apos;), { ssr: false })
 
export default function Page() {
  return (
    &lt;div&gt;
      &lt;NoSSR /&gt;
    &lt;/div&gt;
  )
}
// language: js
import dynamic from &apos;next/dynamic&apos;
 
const NoSSR = dynamic(() =&gt; import(&apos;../components/no-ssr&apos;), { ssr: false })
 
export default function Page() {
  return (
    &lt;div&gt;
      &lt;NoSSR /&gt;
    &lt;/div&gt;
  )
}
```
5. Use [`suppressHydrationWarning`](https://nextjs.org/docs/messages/react-hydration-error#solution-3-using-suppresshydrationwarning).
    - When text or attributes are unavoidably different between the server and the client, you can use [`suppressHydrationWarning`](https://nextjs.org/docs/messages/react-hydration-error#solution-3-using-suppresshydrationwarning) to prevent the error from showing for that specific component.
```
// language: ts
// Silence warnings on elements with intentionally dynamic text
&lt;span suppressHydrationWarning&gt;
  {new Date().toLocaleTimeString()}
&lt;/span&gt;
// language: js
// Silence warnings on elements with intentionally dynamic text
&lt;span suppressHydrationWarning&gt;
  {new Date().toLocaleTimeString()}
&lt;/span&gt;
```
- *Proceed with caution, though! It does not actually fix the structural mismatch but just silences the error. It should be used sparingly.*</content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js: What Are React Hooks and How Do They Work?]]></title>
            <description><![CDATA[An overview of what React hooks are, how they are used, and a look at what the most common hooks are.]]></description>
            <link>https://www.taqtiq.tech/blog/nextjs-what-are-react-hooks-and-how-do-they-work</link>
            <guid isPermaLink="false">j978cjpt7dwa38mjfyy7z2kpy18fa08s</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[tutorials]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 01:59:27 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/abde1919-245a-4a67-8427-209200b699e0" length="0" type="audio/mpeg"/>
            <content:encoded>## What are hooks?

- React hooks are functions that allow you to &quot;hook into&quot; React state and lifecycle features.
- Hooks allow you to manage local state, run side effects, access context, and optimise performance.
- In Next.js hooks work the same as in React.
- In Next.js, hooks can only be used in client components (components marked with the `&apos;use client&apos;` directive) because they need to tap into client side interactivity (clicking a button, typing an input, etc) and rely on browser APIs and component lifecycle events that only exist in the browser.

## What are the rules of hooks?

- There are **two main rules of hooks**:

1. **Only call hooks at the top level.**
    - Do not call hooks inside loops (`for`, `while`), conditions (`if`, `switch`), or nested functions. Only use hooks at the top level of your React function, before any early returns.
2. **Only call hooks from React functions.**
    - Do not call hooks from regular JavaScript functions. You should only call hooks from:
    1. **React function components** (components that return JSX).
    2. **Custom hooks** (functions whose name start with `use`).

## Why do these rules exist?
1. **React relies on call order to track state.**
    - React does not use key names to match `useState` or `useEffect` calls to their stored values.
    - Instead, React maintains an internal array of state pairs for each component. It relies entirely on the **exact order** in which hooks are called on every single render.
    - If a hook is placed inside an `if` statement that only evaluates to `true` on *some* renders, the sequence of hook calls changes.
    - By forcing hooks to be called at the top level, React guarantees that hooks run in the exact same order on every render.
2. **Scope isolation.**
    - Restricting hooks to functional components and custom hooks ensures that state, side effects, and lifecycle behaviours remain strictly scoped to React&apos;s component tree and runtime memory.
3. **Predictability and static analysis.**
    - Standardising these rules enables automated tooling (like the official `eslint-plugin-react-hooks`) to analyse code at compile time and automatically catch potential state bugs before code ever reaches production.

Here is an overview of some common hooks in Next.js, how they work and what they do:

## useState
- The `useState` hook is React&apos;s primary mechanism for giving functional components their own memory.
- It lets a component hold onto data across renders and triggers a UI update whenever that data changes.

### Syntax
You import `useState` from `react` and call it inside a component:

```
// language: ts
// title: Counter.tsx
import { useState } from &apos;react&apos;;

function Counter() {
  const [count, setCount] = useState(0);

  return (
    &lt;button onClick={() =&gt; setCount(count + 1)}&gt;
      Count: {count}
    &lt;/button&gt;
  );
}
// language: js
// title: Counter.jsx
import { useState } from &apos;react&apos;;

function Counter() {
  const [count, setCount] = useState(0);

  return (
    &lt;button onClick={() =&gt; setCount(count + 1)}&gt;
      Count: {count}
    &lt;/button&gt;
  );
}
```
- **Initial argument (0):** The starting value for the variable on the components initial render.
- **Return value (array destructuring):** `useState` returns an array with exactly two elements:
    1. **The current state value (count):** holds the value for the *current* render.
    2. **The state setter function (setCount):** Updates the state and tells React to queue a re-render.

![useState()](/api/storage/kg24p195mc21794byxqvm5v00s8gzyx3)

### How `useState` works
- In Next.js, every time a component re-renders, the function runs from to bottom. Meaning all local variables inside it are wiped and recreated.
- `use state` gets around this by storing state **outside** your function component and inside React&apos;s hidden internal memory.
#### On first render:
1. React creates a state cell in memory.
2. It assigns the initial value (0) to that cell.
3. It returns [0, setCount].
#### On subsequent renders:
 1. React ignores the initial value.
 2. It looks up the cell based on the order it was called.
 3. It returns the updated value saved in memory alongside the setter function.

- Calling the setter function (`setCount(1)`) does two things:
1. It updates the state value stored in React&apos;s internal memory cell.
2. It flags the component as &quot;dirty&quot; and schedules a re-render.

### Key things to keep in mind:
1. State updates are asynchronous. This means that setting state does not immediately change the variable in the current line of code. Instead, it triggers a re-render:

```
// language: ts
const [count, setCount] = useState(0);

function handleClick() {
  setCount(count + 1);
  console.log(count); // Still prints 0. Value updates on next render.
}

// language: js
const [count, setCount] = useState(0);

function handleClick() {
  setCount(count + 1);
  console.log(count); // Still prints 0. Value updates on next render.
}
```
2. If your new state depends on the previous state, pass a function to the setter instead of the raw value. This ensures you are working with the most up to date state:

```
// language: ts
setCount(prevCount =&gt; prevCount + 1);
// language: js
setCount(prevCount =&gt; prevCount + 1);
```
3. **Objects and arrays must be replaced, not mutated:** React checks if state changed using strict equality (`Object.is`). If you mutate an object directly, React will not trigger a re-render:

```
// language: ts
// ❌ Won&apos;t trigger a re-render:
user.name = &apos;Alice&apos;;
setUser(user);

// ✅ Triggers a re-render:
setUser({ ...user, name: &apos;Alice&apos; });
// language: js
// ❌ Won&apos;t trigger a re-render:
user.name = &apos;Alice&apos;;
setUser(user);

// ✅ Triggers a re-render:
setUser({ ...user, name: &apos;Alice&apos; });
```

4. **Lazy initialisation:** 
    - When you pass a value or the result of a function call directly into `useState`, the expression is evaluated on **every single render:**
 
```
// language: ts
// ❌ Without Lazy Initialization
const [data, setData] = useState(calculateHeavyInitialData());
// language: js
// ❌ Without Lazy Initialization
const [data, setData] = useState(calculateHeavyInitialData());
```

- **Initial render:** React calls `calculateHeavyInitialData()`, gets the value and stores it in state.
- **Re-render 1:** `calculateHeavyData()` is ran *again* before calling `useState`. React sees it already has state saved from the first render, **discards** the new value and moves on.
- **Re-render 2:** It runs *again*, and gets discarded *again*.
- If `calculateHeavyData()` contains heavy computations, you are slowing down your application for a calculation that React completely ignores.

![First Render](/api/storage/kg2cdtkv8ckws25bnzfwxtphgx8gycpz)

![Subsequent Renders](/api/storage/kg23e84ydpxj0yyrt868n5bza18gyq79)

- To solve this, you should pass an anonymous function in instead:
```
// language: ts
// ✅ With Lazy Initialization
const [data, setData] = useState(() =&gt; calculateHeavyInitialData());
// language: js
// ✅ With Lazy Initialization
const [data, setData] = useState(() =&gt; calculateHeavyInitialData());
```
**Now:**
1. **Initial render:** React calls the function `() =&gt; calculateHeavyInitialData()`, gets the state and saves it.
2. **Subsequent renders:** React skips the initialiser function entirely because the state is already initialised. `calculateHeavyInitialData()` is never executed again.

## useEffect
- `useEffect` is Reacts tool for managing **side effects**.
- Side effects are operations that interact with the world outside of a components rendering loop (e. g. fetching data, setting timers or manually accessing the browser DOM).

### Syntax
- `useEffect` takes two parameters:
    1. A **callback function** (the effect).
    2. An **optional dependency array**. 
 ```
// language: ts
import { useEffect, useState } from &apos;react&apos;;

function UserProfile({ userId }) {
    const [user, setUser] = useState(null);

    useEffect(() =&gt; {
        // 1. The Effect: Code that runs AFTER render
        fetchUserData(userId).then(data =&gt; setUser(data));

        // 2. The Cleanup (Optional): Code that runs before unmount/re-effect
        return () =&gt; {
            console.log(&apos;Cleaning up old user fetch...&apos;);
        };
    }, [userId]); // 3. The Dependency Array: Controls when the effect runs
}
// language: js
import { useEffect, useState } from &apos;react&apos;;

function UserProfile({ userId }) {
    const [user, setUser] = useState(null);

    useEffect(() =&gt; {
        // 1. The Effect: Code that runs AFTER render
        fetchUserData(userId).then(data =&gt; setUser(data));

        // 2. The Cleanup (Optional): Code that runs before unmount/re-effect
        return () =&gt; {
            console.log(&apos;Cleaning up old user fetch...&apos;);
        };
    }, [userId]); // 3. The Dependency Array: Controls when the effect runs
}
```
- The second argument controls the lifecycle behaviour of the effect.
- There are three different variations:
    1. **No dependency array (runs on every render):**
     ```
     // language: ts
     useEffect(() =&gt; {
         console.log(&apos;Component rendered or re-rendered.&apos;);
     });
     // language: js
     useEffect(() =&gt; {
         console.log(&apos;Component rendered or re-rendered.&apos;);
     });
     ```
     - Executes after the initial render **and on every subsequent render**.
    2. **Empty dependency array:**
    ```
     // language: ts
    useEffect(() =&gt; {
        console.log(&apos;Component appeared on screen for the first time.&apos;);
    }, []);
     // language: js
    useEffect(() =&gt; {
        console.log(&apos;Component appeared on screen for the first time.&apos;);
    }, []);
    ```
    - This runs **only once** after the initial render (when the component mounts to the screen)
    3. **Dependencies included [a, b] (runs on mount and dependency changes):**
    ```
     // language: ts
    useEffect(() =&gt; {
        console.log(`userId changed to ${userId}, fetching new data...`);
    }, [userId]);
     // language: js
    useEffect(() =&gt; {
        console.log(`userId changed to ${userId}, fetching new data...`);
    }, [userId]);
    ```
    - Runs on mount and then re-runs **only if** one of the values in the array (`userId`) changes between renders.

#### The cleanup function:
- If your effect returns a function, React treats it as a cleanup routine.
```
// language: ts
useEffect(() =&gt; {
  const timer = setInterval(() =&gt; {
    console.log(&apos;Tick&apos;);
  }, 1000);

  // Cleanup function:
  return () =&gt; {
    clearInterval(timer);
  };
}, []);
// language: js
useEffect(() =&gt; {
  const timer = setInterval(() =&gt; {
    console.log(&apos;Tick&apos;);
  }, 1000);

  // Cleanup function:
  return () =&gt; {
    clearInterval(timer);
  };
}, []);
```
- React executes the cleanup function in two situations:
1. **Before running the effect again** (when dependencies change), to clean up the previous renders side effects.
2. **When the component unmounts** (it is removed from the screen).

#### Common cleanup examples:
- Clearing timers (`clearInterval`, `clearTimeout`).
- Unsubscribing from WebSockets or event listeners (`removeEventListener`).
- Aborting ongoing HTTP fetch requests (`AbortController`).

#### How `useEffect` works
- The execution of `useEffect` is deferred.
1. **Render step:** React executes the function component body, generates the JSX, updates the DOM, and paints the screen for the user.
2. **Browser paint:** The user immediately sees the visual changes on their screen.
3. **Effect step:** React runs the `useEffect` callback asynchronously in the background so that it doesn&apos;t block or slow down screen rendering.

### Key things to keep in mind:
- **Include all used values in dependencies:** If the effect uses a variable from the component scope (props or state), it **must** be listed in the dependency array. Leaving it out leads to &quot;stale closure&quot; bugs where the effect references outdated data.
- **Avoid infinite loops:** `useEffect` can trigger infinite loops when the same state variable is listed in the dependency array without a conditional check:
```
// language: ts
// ❌ Infinite loop: 
useEffect(() =&gt; {
  setCount(count + 1);
}, [count]);
// language: js
// ❌ Infinite loop: 
useEffect(() =&gt; {
  setCount(count + 1);
}, [count]);
```
- **Don&apos;t use `useEffect` for transforming data:** You don&apos;t need `useEffect` to transform state before rendering. Calculate derived data directly in the body of the function or use `useMemo` instead.

## useContext
- `useContext` is Reacts built in method for sharing data globally across the component tree.
- It is the solution for a common issue known as **&quot;prop drilling&quot;**.
[prop3.drawio]
### Syntax
- Setting up and using `useContext` requires three parts:
1. **Creating**
2. **Providing**
3. **Consuming**.

#### 1. Creating the context
- Create a `Context` object using `createContext`. This is usually placed in its own file or at the top level of a module:
```
// language: ts
import { createContext } from &apos;react&apos;;

// Create context with an optional default value
export const ThemeContext = createContext(&apos;light&apos;);
// language: js
import { createContext } from &apos;react&apos;;

// Create context with an optional default value
export const ThemeContext = createContext(&apos;light&apos;);
```

#### 2. Providing the context
- Wrap the component subtree that needs access to the data in a `&lt;Context.Provider&gt;` and pass the data you want to share into its value prop:
```
// language: ts
import { useState } from &apos;react&apos;;
import { ThemeContext } from &apos;./ThemeContext&apos;;
import Navigation from &apos;./Navigation&apos;;

function App() {
  const [theme, setTheme] = useState(&apos;dark&apos;);

  return (
    // Any component inside ThemeContext.Provider can now access `theme`
    &lt;ThemeContext.Provider value={{ theme, setTheme }}&gt;
      &lt;Navigation /&gt;
    &lt;/ThemeContext.Provider&gt;
  );
}
// language: js
import { useState } from &apos;react&apos;;
import { ThemeContext } from &apos;./ThemeContext&apos;;
import Navigation from &apos;./Navigation&apos;;

function App() {
  const [theme, setTheme] = useState(&apos;dark&apos;);

  return (
    // Any component inside ThemeContext.Provider can now access `theme`
    &lt;ThemeContext.Provider value={{ theme, setTheme }}&gt;
      &lt;Navigation /&gt;
    &lt;/ThemeContext.Provider&gt;
  );
}
```
#### Consuming the `Context` with `useContext`
- Inside any child component wrapped with that Provider, you can now call `useContext` and pass in the `Context` object created in step 1:
```
// language: ts
import { useContext } from &apos;react&apos;;
import { ThemeContext } from &apos;./ThemeContext&apos;;

function ThemeToggleButton() {
  // Read both theme and setTheme directly from ThemeContext
  const { theme, setTheme } = useContext(ThemeContext);

  return (
    &lt;button onClick={() =&gt; setTheme(theme === &apos;light&apos; ? &apos;dark&apos; : &apos;light&apos;)}&gt;
      Current Theme: {theme}
    &lt;/button&gt;
  );
}
// language: js
import { useContext } from &apos;react&apos;;
import { ThemeContext } from &apos;./ThemeContext&apos;;

function ThemeToggleButton() {
  // Read both theme and setTheme directly from ThemeContext
  const { theme, setTheme } = useContext(ThemeContext);

  return (
    &lt;button onClick={() =&gt; setTheme(theme === &apos;light&apos; ? &apos;dark&apos; : &apos;light&apos;)}&gt;
      Current Theme: {theme}
    &lt;/button&gt;
  );
}
```

### Key things to keep in mind:
- When the value prop passed to `&lt;Context.Provider&gt;` changes, every component that calls `useContext` for that specific Context will automatically re-render with the updated value.
- If a component calls `useContext(ThemeContext)` but is not rendered inside a matching `&lt;ThemeContext.Provider&gt;`, it will fall back to the default value defined inside `createContext(...)`.
- Components can consume as many contexts as needed:
```
// language: ts
const user = useContext(UserContext);
const theme = useContext(ThemeContext);
// language: js
const user = useContext(UserContext);
const theme = useContext(ThemeContext);
```</content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Next.js Caching]]></title>
            <description><![CDATA[An in-depth look at caching in Next.js, explaining the history of caching and the modern caching strategy with Partial Prerendering and cache components. ]]></description>
            <link>https://www.taqtiq.tech/blog/understanding-nextjs-caching</link>
            <guid isPermaLink="false">j970f1zady4xnxfm4zkhzrc7v58f1g89</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[tutorials]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Thu, 24 Sep 2026 15:32:37 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/fcec7c88-0ccf-4a20-b50c-912edbed8eba" length="0" type="audio/mpeg"/>
            <content:encoded>## What is caching? (a brief overview)

- Caching is the process of storing copies of frequently accessed data in a fast, temporary storage layer (a **cache**), so that future requests can serve that data much faster than fetching it from the primary source.

### With caching (fast)

![With Caching (Fast)](/api/storage/kg27dc5r7ft02ahkwvzj6pny4s8gzcdx)

### Without caching (slow)

![Without Caching (Slow)](/api/storage/kg26cbt9wv5m10he0yx1e9ea3h8gyrnx)

- Many webpage resources rarely change, so storing them in fast temporary memory avoids slow, repeated database queries:

![Cached Page Elements](/api/storage/kg25wc5secex1cxxvgnpy40fb98gy1p2)

## The evolution of caching in Next.js:

- To understand the core of how caching works in Next.js, it is first important to understand a bit of historical context.
- This builds the basis for understanding why caching works the way it does today.

### Next.js 14
- **Next.js 14 cached aggressively by default**.
- `fetch` was cached by default (`force-cache`).
- Every page was static and cached by default unless you used one of these three functions (that made the route dynamic):
    1. `cookies()`
    2. `headers()`
    3. `searchParams()`
    
- If a user clicked a `&lt;Link&gt;`, Next.js stored the React Server Component (RSC) payload directly inside the user&apos;s browser memory.
    1. **Static routes**: Cached in the browser for 5 minutes.
    2. **Dynamic routes**: Cached in the browser for 30 seconds.

- Even if your backend server had fresh data, a user navigating between pages within the 30 second to 5 minute window would see old, cached UI from their browsers memory without a server request being made.

- `GET` route handlers were statically cached at build time by default, unless you explicitly opted out with dynamic functions (like `cookies()`), or added `export const dynamic = &apos;force-dynamic&apos;`.
    1. An endpoint returning dynamic data like `Response.json({ time: Date.now() })` would serve the exact same frozen timestamp to every user.

**Why they did it:**
They wanted apps to be blazingly fast out of the box by generating static pages whenever possible.

**Why it backfired:**
Unexpected stale data: Developers would fetch something dynamic (like a user profile, stock price, or real-time feed), and it would render once at build time and never update unless manually revalidated.

**Confusion with standard JS:** In standard JavaScript, `fetch()` goes to the network every single time. Next.js overriding this standard web behavior caused endless debugging sessions.

**Opt-out fatigue:** Developers had to explicitly write `{ cache: &apos;no-store&apos; }` on almost every fetch call just to get normal HTTP behavior.

### Next.js 15+:
- To address the aforementioned issues, Next.js 15 adopted an **uncached by default** model which persists to this day.
- `fetch` requests became **uncached by default** (`no-store`), with data being fetched fresh on every request unless you explicitly add `{ cache: &apos;force-cache&apos; }` or set `next: { revalidate: X }`.
- `GET` route handlers became uncached by default - to make a route handler static, you now have to write `export const dynamic = &apos;force-static&apos;`.
- The default `staleTime` for dynamic components is now set to 0 seconds. Meaning that navigating between pages re-fetches the latest data from the server by default.
- Runtime request-specific APIs (like `cookies()`, `headers()`, `params` and `searchParams()`) were turned into asynchronous promises.
- Next.js 15 introduced the experimental `&apos;use cache&apos;` directive to give the developer greater, explicit, fine-grained control over what should be cached. This would be later refined in Next.js 16.

## Next.js 16 and the introduction of cache components

- Cache components were introduced as an experimental feature in Next.js 15 with the `&apos;use cache&apos;` directive.
- It allowed developers to opt individual components, functions, or files into caching while keeping the rest of the application dynamic by default.
- In Next.js 16, `&apos;use cache&apos;` was refined and unified with Partial Prerendering (PPR).
- To understand cache components, it is first important to understand what Partial Prerendering is.

### Partial prerendering (PPR)

&gt; Partial Prerendering (PPR) combines static and dynamic rendering in a single route. At build time, Next.js generates a static HTML shell and a `postponedState` blob for each PPR-enabled route. At request time, the shell is served immediately and dynamic portions are rendered and streamed to the client.

[Partial Prerendering](https://nextjs.org/docs/app/guides/ppr-platform-guide)

- The general idea being that instead of opting an *entire* route into static or dynamic rendering, with PPR, you can make different components static or dynamic within the same route (you don&apos;t have to choose one or the other).
- With PPR, you get the benefits of static rendering (improved performance, content served instantly from a CDN) and dynamic rendering (real-time data feeds) on the same route.

![Partial Prerendering](/api/storage/kg2e30zf1tdtrgk8qvyjxy4t7s8gy2sz)

- **Build time:** at build time, the static shell is prerendered. Where dynamic components sit inside a `&lt;Suspense&gt;` fallback, Next.js leaves a lightweight placeholder slot.
- **Request time:** When a user requests the page, the server instantly sends the prebuilt static shell. The browser renders the layout and fallback UI (loading skeletons) instantly.
- **Streaming phase:** in the background of that *same connection*, the server executes the async dynamic components and streams the HTML chunks down to fill the placeholder slots as they complete.

![Partial Prerendering with Dynamic Components Streamed in](/api/storage/kg2bka4ezythvagqeksg8kszx58gyrys)

### Example

```
// language: ts
//title: app/page.tsx
import { Suspense } from &apos;react&apos;;
import { StaticHeader } from &apos;@/components/Header&apos;;
import { ProductDetails } from &apos;@/components/ProductDetails&apos;;
import { CartBadge, CartSkeleton } from &apos;@/components/Cart&apos;;
import { RecommendedProducts, RecsSkeleton } from &apos;@/components/Recs&apos;;

export default function Page() {
  return (
    &lt;main&gt;
      {/* 1. Static: Included in the initial static HTML shell */}
      &lt;StaticHeader /&gt;
      &lt;ProductDetails /&gt;

      {/* 2. Dynamic: Suspended boundary turned into a dynamic stream slot */}
      &lt;Suspense fallback={&lt;CartSkeleton /&gt;}&gt;
        &lt;CartBadge /&gt; {/* Reads cookies / user session */}
      &lt;/Suspense&gt;

      {/* 3. Dynamic: Streams independently from the cart */}
      &lt;Suspense fallback={&lt;RecsSkeleton /&gt;}&gt;
        &lt;RecommendedProducts /&gt; {/* Slow database query */}
      &lt;/Suspense&gt;
    &lt;/main&gt;
  );
}
```

### Cache components
- Partial Prerendering was initially introduced as a rendering model to solve the problem of routes needing to be 100% static or 100% dynamic.
- Cache components were later introduced to unify Next.js&apos;s caching strategy with this model.
- Cache components are the primary way that Next.js caching works today.

- To enable cache components, set the `cacheComponents` flag to `true` in your applications `next.config.ts` file:

```
// language: ts
// title: next.config.ts
import type { NextConfig } from &apos;next&apos;
 
const nextConfig: NextConfig = {
  cacheComponents: true,
}
 
export default nextConfig
```

- With cache components enabled, you will now be able to use three different functions:
1. The `&apos;use cache&apos;` directive.
2. The `cacheLife` function with `&apos;use cache&apos;`.
3. The `cacheTag` function.

### The `&apos;use cache&apos;` directive
- The `&apos;use cache&apos;` directive allows you to mark a **route**, **component** or **function** as cacheable.

### Function level
- You can cache the output of slow computations, database queries or external API calls.
```
// language: ts
//title: lib/data.ts
import { cacheLife } from &apos;next/cache&apos;;

export async function getUserProfile(userId: string) {
  &apos;use cache&apos;;

  const user = await db.user.findUnique({ where: { id: userId } });
  return user;
}
```

### Component level
- You can cache the rendered output of a server component. If the props do not change, Next.js skips running the component logic and serves the cached result.
```
// language: ts
//title: components/RecommendedProducts.tsx
export async function RecommendedProducts({ category }: { category: string }) {
  &apos;use cache&apos;;

  const products = await fetchProductsByCategory(category);

  return (
    &lt;div&gt;
      {products.map((item) =&gt; (
        &lt;ProductCard key={item.id} product={item} /&gt;
      ))}
    &lt;/div&gt;
  );
}
```

### Route level
- Adding `&apos;use cache&apos;` at the top of a `page.tsx` for `layout.tsx` file caches everything exported from that file, rendering it statically.
```
// language: ts
//title: app/blog/[slug]/page.tsx
&apos;use cache&apos;;

export default async function BlogPost({ params }: { params: { slug: string } }) {
  const post = await getPost(params.slug);
  return &lt;article&gt;{post.content}&lt;/article&gt;;
}
```

- `&apos;use cache&apos;` can be used at the top of a file to indicate that all exports in the file should be cached, or inline at the top of a function or component to cache the return value.
- Functions and components that use `&apos;use cache&apos;` should always be async.

### The `cacheLife` function with `use cache`
- The `cacheLife` function is used to set the cache lifetime of a function or component. 
- It should be used in conjunction with the `&apos;use cache&apos;` directive, and within the scope of the function or component.

```
// language: ts
// title: app/blog/page.tsx
&apos;use cache&apos;
import { cacheLife } from &apos;next/cache&apos;
 
export default async function BlogPage() {
  cacheLife(&apos;days&apos;) // Blog content updated daily
 
  const posts = await getBlogPosts()
  return &lt;div&gt;{/* render posts */}&lt;/div&gt;
}
```
- Essentially, it is used alongside `&apos;use cache&apos;` to determine how long a specific function, component or route should stay cached for and when it should revalidate.
- `cacheLife` has three different timers:
    1. `stale` (stale while revalidate): How long the cached response is considered fresh. During this time, users get the cached response immediately but data may be outdated.
    2. `revalidate`: The window where Next.js continues to serve the stale cache while silently fetching fresh data in the background.
    3. `expire`: The maximum time an entry can sit unused in cache before it is discarded and forces a fresh request on the next visit.

Next.js has different `cacheLife` profiles so you don&apos;t have to remember exact second counts:

![Cachelife Profiles](/api/storage/kg2cftkq4tgd6wvd9xvg41j22d8fzcvs)

But you can specify exact numbers if you wish:

```
// language: ts
cacheLife({ stale: 300 }) // 5 minutes
cacheLife({ revalidate: 900 }) // 15 minutes
cacheLife({ expire: 3600 }) // 1 hour
```

### The `cacheTag` function with `use cache`
- While `cacheLife` manages time based revalidation (e.g., &quot;expire after 10 minutes&quot;), `cacheTag` allows for on-demand revalidation.
- It lets you purge specific items from the cache immediately when an event occurs, such as a user submitting a form or a CMS webhook firing.

### Example

- You can mark a function or component with `&apos;use cache&apos;` and assign it a `cacheTag`:

```
// language: ts
//title: app/actions/products.ts
import { cacheTag } from &apos;next/cache&apos;;

export async function getProductDetails(productId: string) {
  &apos;use cache&apos;;
  
  // Tag this specific product AND tag the overall product collection
  cacheTag(&apos;products&apos;, `product-${productId}`);

  return await db.product.findUnique({ where: { id: productId } });
}
```

- You can then revalidate that tag on-demand:
```
// language: ts
//title: app/actions/admin.ts
&apos;use server&apos;;

import { revalidateTag } from &apos;next/cache&apos;;

export async function updateProduct(productId: string, newData: any) {
  await db.product.update({
    where: { id: productId },
    data: newData,
  });

  // Instantly purges any cache entry tagged with `product-${productId}`
  revalidateTag(`product-${productId}`);
}
```</content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js: Why You Shouldn't Use a Global /components Folder for Everything]]></title>
            <description><![CDATA[Exploring a common mistake when structuring a Next.js project with the app router and explaining what you should actually be doing to ensure your project is clean.]]></description>
            <link>https://www.taqtiq.tech/blog/nextjs-why-you-shouldnt-use-a-global-components-folder-for-everything</link>
            <guid isPermaLink="false">j97cskd3xz7b3pktp9gk9fd7kx8eeqvk</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[opinion]]></category>
            <category><![CDATA[tutorials]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 21:04:52 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/2f7e4b6a-b3c4-4edd-ae15-dd29c36e127c" length="0" type="audio/mpeg"/>
            <content:encoded>- One crucial mistake I made when working on my first Next.js project was to place all my components in a root `/components` folder.
- This wasn&apos;t a problem for a while, because I didn&apos;t have many components at the start so the structure of my project was quite clear and easy to understand.
- However, as my project grew, I just kept adding more and more components to the same root `/components` folder and I started to get a nagging sense that it wasn&apos;t the most effective way of structuring a project.
- Nothing was organised properly, so I would spend ages scrolling and sifting through components that weren&apos;t at all related to the problem I was trying to solve, just to find what I needed.

![Monolithic Components Structure](/api/storage/kg20gv8rf3r3jm8j9r6jcx00yh8gyym6)

### Example of ineffective folder structure using root `/components` folder:

![Poor Folder Structure](/api/storage/kg29mmkkykgs3fxa3tw76bwt8s8gz1gf)

- This common anti-pattern places all components together in a single root `/components` folder.
1. It mixes components that are used in different pages with each other in the same directory and doesn&apos;t distinguish between components that are used globally or only in a specific page.
2. Rather than grouping related components together with the page that they are used in.

## So what is the solution?

- When reading the documentation in greater detail, I learnt about the existence of &quot;Private folders&quot;.
- Private folders are folders that are ignored by the router. Meaning that you cannot navigate to them with a URL.
- You can create private folders by prefixing a folder name with an underscore - `_folder`.
- Going to `app/dashboard/_components` for instance will return a 404 error.

### Example of corrected folder structure using private files:

![Corrected Folder Structure](/api/storage/kg29tsnwphdbwp74k599b5g4js8gyxsx)

- The solution to our original issue of having a monolithic root `/components` folder is to colocate (group) components together with the pages they are used in by using private files.
- The root `/components` folder should instead only be used for global components (components that need to be used in *several* pages).



</content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js Server Components Vs Client Components: a Decision Framework]]></title>
            <description><![CDATA[A look at server components vs client components, an explanation of when to use each, and explaining a common anti-pattern.]]></description>
            <link>https://www.taqtiq.tech/blog/nextjs-server-components-vs-client-components-a-decision-framework</link>
            <guid isPermaLink="false">j976kpzqv7c68ptpdbzk2es44x8e0cbs</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[tutorials]]></category>
            <dc:creator><![CDATA[Emmanuel Learmount]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 23:04:41 GMT</pubDate>
            <enclosure url="https://proficient-fly-549.eu-west-1.convex.cloud/api/storage/bb4ef2d9-96fd-4514-9a42-969fda6b494f" length="0" type="audio/mpeg"/>
            <content:encoded>- In Next.js, the general rule of thumb is to use client components as sparingly as possible.
- This is because larger client bundles require more JS hydration, hurting your [Interaction to Next Paint (INP)](https://web.dev/articles/inp) and [Time to Interactive (TTI)](https://web.dev/articles/tti).
- Meaning that the perceived performance of your website will suffer if client components are used excessively.

- Sometimes client components *will* need to be used, as your site will likely have to make use of features that are only available in the clients’ browser. Such as:

![Client Features](/api/storage/kg291k1wzywrke8qtxcdes4gv18g0v4b)

- In this case, when creating client components, it is important not to fall for a common anti-pattern that will negatively impact your sites performance:
1. The &quot;use client&quot; directive opts all child components into client-side rendering.
2. It is therefore very easy to accidentally opt several components into client-side rendering, even if they don’t necessarily *need* to be rendered on the client.
3. This will affect your site&apos;s [Interaction to Next Paint (INP)](https://web.dev/articles/inp) and [Time to Interactive (TTI)](https://web.dev/articles/tti), negatively impacting the performance for the end user.

![&quot;use client&quot; Chain](/api/storage/kg29f01sed2re0xxyhddp0v3md8gz0at)

### Example

#### Anti-pattern

```
// language: ts
// Anti-pattern: Marking the parent page with &quot;use client&quot;
&quot;use client&quot;

import { useState } from &apos;react&apos;
import Header from &apos;./Header&apos; // Forced into client bundle
import ArticleContent from &apos;./ArticleContent&apos; // Forced into client bundle

export default function BlogPost() {
  const [isOpen, setIsOpen] = useState(false)

  return (
    &lt;main&gt;
      &lt;Header /&gt;
      &lt;button onClick={() =&gt; setIsOpen(!isOpen)}&gt;Toggle Sidebar&lt;/button&gt;
      &lt;ArticleContent /&gt; 
    &lt;/main&gt;
  )
}
```

The anti-pattern appears when you opt content into client-side rendering that is better placed on the server. In the case above, `Header` and `ArticleContent` should be rendered on the server as they do not make use of any client side features. Therefore, placing them on the client will increase bundle size unnecessarily. 

- In order to preserve your sites performance, you should localise the “use client” directive, so that only code that is essential to run on the client does so.
- The most common case is that a component will contain a mix of functionality that should run on the server and that can only run on the client.
- In this case, for maximum performance you should create new components and mark them with the “use client” directive with only the essential functionality that needs to run on the client.

![Anti-Pattern VS Correct Pattern](/api/storage/kg2c4awpjhvdm6xb6gy1hb6sts8gy42q)

### Solution
#### Correct design pattern

```
// language: ts
// 1. Client Component: Handles only the interactive button
// SidebarToggle.tsx
&quot;use client&quot;

import { useState } from &apos;react&apos;

export function SidebarToggle() {
  const [isOpen, setIsOpen] = useState(false)
  return &lt;button onClick={() =&gt; setIsOpen(!isOpen)}&gt;Toggle Sidebar&lt;/button&gt;
}
```

```
// language: ts
// 2. Server Component: Keeps heavy content and headers on the server
// BlogPost.tsx (No &quot;use client&quot; directive)
import Header from &apos;./Header&apos; // Stays a Server Component
import ArticleContent from &apos;./ArticleContent&apos; // Stays a Server Component
import { SidebarToggle } from &apos;./SidebarToggle&apos;

export default function BlogPost() {
  return (
    &lt;main&gt;
      &lt;Header /&gt;
      &lt;SidebarToggle /&gt;
      &lt;ArticleContent /&gt;
    &lt;/main&gt;
  )
}
```

The correct implementation moves the `&lt;button&gt;` to a new component (`SidebarToggle.tsx`) which is marked with the `&quot;use client&quot;` directive. This is because the button needs to access mouse events which are only available on the client to process the click.

At the same time, `Header` and `ArticleContent` are left out of client-side rendering so that the bundle size stays as small as possible and the site&apos;s performance is preserved.</content:encoded>
        </item>
    </channel>
</rss>