Courses / Frontend System Design, with JavaScript Foundations / Chapter 2
Module 2 · JavaScript Foundations · Chapter 2 of 21
Values, Coercion, Scope and Closures
No prerequisites. Next up: this, Prototypes and Classes.
Part 1 · Types and values
Seven primitives and objects
Many frontend bugs start with a value that is not the type the code assumed, such as a price that arrives as a string. This chapter covers how JavaScript values behave, so those bugs stop being surprises.
Every JavaScript value is either a primitive or an object. A primitive is a single value that cannot be changed and has no properties of its own. You can build a new string from an old one, but you cannot change a character inside it. There are seven primitive types.
| Type | Example | Used for |
|---|---|---|
| undefined | undefined | A variable with no value yet, a missing property |
| null | null | An intentional "no value" |
| boolean | true | Flags and conditions |
| number | 42, 3.5, NaN | Every ordinary number, integer or not |
| bigint | 10n | Integers too large for a number |
| string | "hi" | Text |
| symbol | Symbol("id") | Unique keys that cannot clash |
Everything else is an object: plain objects, arrays, functions, dates, maps and sets. An object is a collection of properties that can change, and a variable holds a reference to it, not the object itself. The difference between a value and a reference explains a large share of the surprises in the rest of this chapter.
Asking for the type
The typeof operator returns a string naming the type. Run it over one sample of each kind.
const samples = [ ['undefined', undefined], ['null', null], ['true', true], ['42', 42], ['10n', 10n], ['"hi"', 'hi'], ['Symbol("id")', Symbol('id')], ['{}', {}], ['[]', []], ['function () {}', function () {}], ['class A {}', class A {}], ] for (const [label, v] of samples) { console.log(label.padEnd(16), typeof v) } console.log(Array.isArray([]), [] instanceof Object)
typeof over eleven values
undefined undefined null object true boolean 42 number 10n bigint "hi" string Symbol("id") symbol {} object [] object function () {} function class A {} function true true
Output (Node 24)
Three results surprise people. typeof null is "object". This is a long-standing quirk kept so old pages keep working, not a sign that null is an object, so test it with v === null. A function reports "function" even though functions are objects, and a class is a function as well. An array reports "object", so use Array.isArray to tell it from other objects.
Truthy, falsy and defaults
Conditions such as if and && need a boolean, so JavaScript converts any value to one. The language has eight falsy values, meaning they convert to false: false, 0, -0, 0n, the empty string, null, undefined and NaN. Browsers add one legacy oddity, the old document.all object, which is kept falsy so very old pages still work. Every other value is truthy, including some that look empty.
const values = [false, 0, -0, 0n, '', null, undefined, NaN] console.log(values.map((v) => Boolean(v)).join(' ')) const others = ['0', 'false', [], {}, -1, ' '] console.log(others.map((v) => Boolean(v)).join(' ')) const qty = 0 console.log(qty || 10, qty ?? 10) const label = '' console.log(label || 'none', label ?? 'none')
Falsy values and two ways to set a default
false false false false false false false false true true true true true true 10 0 none
Output (Node 24)
The first line is the eight falsy values; the second shows that "0", "false", an empty array, an empty object, -1 and a single space are all truthy. The last two lines compare defaults. qty || 10 replaces a valid quantity of 0 with 10, because 0 is falsy. qty ?? 10, the nullish coalescing operator, replaces only null and undefined, so it keeps 0 and the empty string. Use ?? when 0 or an empty string is a real answer, such as a quantity or a search box.
Values, references and wrappers
Assigning a primitive copies the value. Assigning an object copies the reference, so two variables point at one object. Changing it through either name shows through both.
const s = 'abc' console.log(typeof s, typeof new String(s)) console.log(s.toUpperCase()) try { s.extra = 1 } catch (e) { console.log(e.constructor.name + ': ' + e.message) } const o = { name: 'Asha' } const copy = o copy.name = 'Ravi' console.log(o.name) let a = 'x' let b = a b += 'y' console.log(a, b)
Copying values and references, and a property on a string
string object ABC TypeError: Cannot create property 'extra' on string 'abc' Ravi x xy
Output (Node 24)
Two things are happening. When you call s.toUpperCase() on a string, JavaScript wraps the primitive in a temporary String object for the call, then discards it. That is why a string has methods even though it is not an object. And because the string itself is immutable, adding a property to it fails. The module file above runs in strict mode, so the failure is a TypeError. In a classic script that is not in strict mode, the same line does nothing and s.extra reads back as undefined. Running the assignment in a CommonJS file printed exactly that: undefined.
Read more about the types in the MDN data structures guide.
Why does typeof null return "object", and how do you test for null?
- It is a long-standing quirk kept for compatibility, not a sign that null is an object.
- Test with
v === null.
Two variables hold the same object. Changing a property through one: does the other see it?
- Yes. Assigning an object copies the reference, so both names point to one object.
- Primitives are copied by value, so changing a copy of a string never changes the original.
A cart form sends a quantity of 0, and const qty = input.qty || 1 turns it into 1. What went wrong, and what is the fix?
Part 2 · Numbers and strings
One number type, 64 bits
JavaScript has one number type for integers and fractions: a 64-bit binary floating-point value, called a double, defined by the IEEE 754 standard. It stores a sign, an exponent and a fraction in binary. Many decimal fractions, such as 0.1, have no exact binary form, so the stored value is the nearest one that fits.
That gives the classic result. The sum of 0.1 and 0.2 is not exactly 0.3, because both inputs are slightly off and the error shows in the sum. Compare with a small tolerance, never with ===. Integers are exact only up to Number.MAX_SAFE_INTEGER, which is 2 to the power 53 minus 1; beyond that, neighbouring integers collide.
console.log(0.1 + 0.2) console.log(0.1 + 0.2 === 0.3) console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON) console.log(Number.MAX_SAFE_INTEGER) console.log(2 ** 53, 2 ** 53 + 1) console.log(2n ** 53n + 1n) console.log(19.99 * 100) const paise = Math.round(19.99 * 100) console.log(paise, paise * 3) console.log(new Intl.NumberFormat('en-IN').format(12345678.5)) console.log(new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', }).format(paise / 100)) console.log(1 / 0, -1 / 0, 0 / 0, Number.isNaN(0 / 0))
Doubles, safe integers, money and formatting
0.30000000000000004 false true 9007199254740991 9007199254740992 9007199254740992 9007199254740993n 1998.9999999999998 1999 5997 1,23,45,678.5 ₹19.99 Infinity -Infinity NaN true
Output (Node 24)
Money, large integers and formatting
The output shows each effect. 0.1 + 0.2 prints 0.30000000000000004. 2 ** 53 and 2 ** 53 + 1 print the same number, while the BigInt version, written with the n suffix, keeps the exact value. 19.99 * 100 prints 1998.9999999999998, which is why prices should not be multiplied in floating point.
The usual way to handle money is to store whole minor units: paise instead of rupees. Compute in integers, and divide only to display. In the run, Math.round(19.99 * 100) gave 1999 paise, and three of them made 5997. Use BigInt when integers can exceed 2 to the power 53, such as ids from some APIs; it cannot be mixed with ordinary numbers in arithmetic.
Display is the job of Intl.NumberFormat. With the en-IN locale it groups digits the Indian way, so 12345678.5 prints as 1,23,45,678.5, and the rupee currency style printed ₹19.99. Division by zero does not throw: 1 / 0 is Infinity and 0 / 0 is NaN. NaN is the one value not equal to itself, so use Number.isNaN to test for it.
Parsing numbers from text
Values from forms and URLs arrive as strings, so you convert them. Number(text) is strict: it returns NaN if any part is not numeric, and an empty string becomes 0. parseInt(text, 10) and parseFloat(text) read as far as they can and stop at the first bad character. Always pass the radix 10 to parseInt.
console.log(Number('12px'), parseInt('12px', 10), parseFloat('3.5kg')) console.log(Number('1,23,456'), parseInt('1,23,456', 10)) console.log(Number(''), parseInt('', 10), +' 42 ') console.log(parseInt('0x1f'), parseInt('08', 10)) console.log((1.005).toFixed(2), (2.5).toFixed(0), Math.round(2.5)) console.log(Number('1_000'), 1_000) const clean = '1,23,456'.replaceAll(',', '') console.log(Number(clean))
Number, parseInt and parseFloat on messy text
NaN 12 3.5 NaN 1 0 NaN 42 31 8 1.00 3 3 NaN 1000 123456
Output (Node 24)
Indian-style grouping breaks both: Number("1,23,456") is NaN, and parseInt stops at the first comma and returns 1. Remove the separators first, as the last lines do, or parse with a library that knows the locale. Also notice (1.005).toFixed(2) printed 1.00, not 1.01, because the stored value is slightly below 1.005. toFixed is for display; do not use it to round money.
Strings are UTF-16
A JavaScript string is a sequence of 16-bit units in the UTF-16 encoding. The length property counts those units, not what a reader sees as characters. Characters outside the first 65,536 code points use two units, called a surrogate pair. Spreading a string with [...s] walks code points instead. A visible unit built from several code points, such as a Hindi syllable with a vowel sign, is a grapheme cluster, and Intl.Segmenter splits on those.
const emoji = '😀' console.log(emoji.length, [...emoji].length) const word = 'नमस्ते' console.log(word.length, [...word].length) const seg = new Intl.Segmenter('hi', { granularity: 'grapheme' }) console.log([...seg.segment(word)].map((s) => s.segment)) console.log([...seg.segment(word)].length) console.log('a'.codePointAt(0), emoji.codePointAt(0).toString(16)) console.log('b' > 'a', 'B' > 'a', '10' < '9', 10 < 9) console.log(['b', 'a', 'C'].sort()) console.log(['b', 'a', 'C'].sort((x, y) => x.localeCompare(y)))
length, code points and graphemes
2 1 6 6 [ 'न', 'म', 'स्ते' ] 3 97 1f600 true false true false [ 'C', 'a', 'b' ] [ 'a', 'b', 'C' ]
Output (Node 24)
The emoji has length 2 but one code point. The Hindi word has six code points, and the segmenter groups them into three visible units, the last being the four code points of the cluster स्ते. When you truncate text for a card or count characters for a limit, length is wrong for such text; segment first.
Comparison with < and > uses the code unit order, so "B" > "a" is false, and "10" < "9" is true because the first characters are compared. The default sort() does the same, and the sorted list puts "C" before "a". Pass localeCompare for text a person will read.
Why is 19.99 * 100 not 1999, and what is the fix for prices?
- Doubles cannot store 19.99 exactly, so the product is 1998.9999999999998.
- Store whole paise as integers, compute in integers and format only for display.
A Hindi word shows 3 visible units. What do length, [...s] and Intl.Segmenter give?
Part 3 · Coercion and equality
Converting values to primitives
Coercion is the automatic conversion of a value from one type to another. JavaScript does it whenever an operator receives a type it does not expect. The core step is ToPrimitive: an object is turned into a primitive by calling its Symbol.toPrimitive method if it has one, and otherwise valueOf and toString, in an order that depends on a hint, which is "string", "number" or "default".
Operators then follow simple rules. The + operator converts both sides to primitives. If either result is a string, it joins strings; otherwise it adds numbers. Operators like - and * always convert to numbers.
console.log(1 + 2, '1' + 2, 1 + '2', '3' - 1, '3' * '4') console.log(1 + null, 1 + undefined, 1 + true) console.log([] + [], [] + {}, [1, 2] + [3]) console.log(Number(''), Number(' 12 '), Number('12px'), Number([5])) console.log(String(null), String([1, [2, 3]]), String({})) const price = { paise: 4999, valueOf() { return this.paise }, toString() { return 'Rs ' + this.paise / 100 }, } console.log(price + 1, `${price}`, price * 2) const t = { [Symbol.toPrimitive](hint) { return hint }, } console.log(`${t}`, t + '', +t)
Operators, conversions and ToPrimitive
3 12 12 2 12 1 NaN 2 [object Object] 1,23 0 12 NaN 5 null 1,2,3 [object Object] 5000 Rs 49.99 9998 string default NaN
Output (Node 24)
Read the first lines against the rules. 1 + "2" is "12", but "3" - 1 is 2. 1 + null is 1 because null becomes 0, and 1 + undefined is NaN. An empty array becomes an empty string, so [] + [] is empty and [1, 2] + [3] is "1,23". In the last lines, the price object returned its valueOf for + and *, but toString inside a template string, and the Symbol.toPrimitive method saw the hints "string", "default" and "number".
The loose equality algorithm
The == operator compares after converting. The algorithm, summarised from MDN, is short. Values of the same type compare directly; objects are equal only if they are the same reference. null and undefined equal only each other. If one side is an object and the other a primitive, the object is converted with ToPrimitive. A boolean is converted to a number. A string against a number converts the string to a number.
Watch for each conversion before the two sides are finally compared
Read it as steps
Three conversions turn the comparison into 0 == 0.
The scene walks [] == ![]. The operator ! runs first and turns the array, which is truthy, into false. Then each conversion takes a step. Nothing in the comparison is random; every step is a rule. The real lesson is to avoid == except for the one idiom x == null, which is true for both null and undefined.
Four kinds of sameness
JavaScript has four equality algorithms, and different features use different ones. Strict equality (===) compares without conversion and treats NaN as unequal to itself and +0 as equal to -0. Object.is uses SameValue: NaN is equal to itself and +0 differs from -0. SameValueZero is SameValue except that +0 equals -0; includes, Map and Set use it. The method indexOf uses strict equality.
console.log([] == ![]) console.log(![], Number([]), Number(false)) console.log(null == undefined, null == 0, null == false) console.log('' == 0, '0' == false, 'a' == 0) console.log(NaN == NaN, NaN === NaN, Object.is(NaN, NaN)) console.log(0 === -0, Object.is(0, -0)) console.log([NaN].includes(NaN), [NaN].indexOf(NaN)) console.log(new Set([NaN, NaN, 0, -0]).size) const m = new Map([[NaN, 'nan'], [0, 'zero']]) console.log(m.get(NaN), m.get(-0)) console.log({} === {}, [1] == '1', [1, 2] == '1,2')
Which algorithm each feature uses
true false 0 0 true false false true true false false false true true false true -1 2 nan zero false true true
Output (Node 24)
| Feature | Algorithm | NaN equals NaN | +0 equals -0 |
|---|---|---|---|
===, indexOf | Strict equality | No | Yes |
Object.is | SameValue | Yes | No |
includes, Map, Set | SameValueZero | Yes | Yes |
== | Loose equality | No | Yes |
Part 4 · Scope and hoisting
var, let and const
A scope is the region of code where a name can be used. JavaScript has global scope, module scope, function scope and block scope. The keyword you declare with decides which one applies. A var belongs to the nearest function, ignoring blocks. A let or const belongs to the nearest pair of braces. A name declared in an inner scope can shadow, or hide, a name of the same spelling in an outer one.
if (true) { var a = 'var leaks' let b = 'let stays' } console.log(a) console.log(typeof b) let x = 'outer' { let x = 'inner' console.log(x) } console.log(x)
Block scope and shadowing
var leaks undefined inner outer
Output (Node 24)
The var escaped the if block and was readable after it. The let did not, so typeof b printed undefined (the name does not exist, and typeof is safe for undeclared names). The inner x shadowed the outer one only inside its braces. Prefer const by default, let when you must reassign, and avoid var.
Hoisting and the temporal dead zone
Before running any code, JavaScript scans a scope and creates its bindings. This is hoisting. A function declaration is hoisted with its body, so you can call it above its definition. A var is hoisted and set to undefined. A let or const is also hoisted but left uninitialised, and touching it before its declaration line throws. The span between the start of the scope and that line is the temporal dead zone.
console.log(typeof hoistedFn, typeof expr, v) function hoistedFn() {} var expr = function () {} var v = 1 try { console.log(typeof tdz) let tdz = 1 } catch (e) { console.log(e.constructor.name + ': ' + e.message) } try { console.log(late) } catch (e) { console.log(e.message) } const late = 1 try { const k = 1 k = 2 } catch (e) { console.log(e.message) } const frozen = { n: 1 } frozen.n = 2 console.log(frozen.n) try { undefinedName } catch (e) { console.log(e.message) }
Hoisting, the dead zone and const
function undefined undefined ReferenceError: Cannot access 'tdz' before initialization Cannot access 'late' before initialization Assignment to constant variable. 2 undefinedName is not defined
Output (Node 24)
The first line shows three kinds of hoisting: the function declaration is a function, the function expression assigned to a var is undefined because only the var was hoisted, and v is undefined before its assignment. Next, even typeof throws inside the dead zone, a case where it is not safe. The message is Cannot access 'tdz' before initialization.
A const binding cannot be reassigned, and the error says so: Assignment to constant variable. But const protects the binding, not the value. The object it points to can still change, which is why frozen.n = 2 printed 2. A name that is declared nowhere throws undefinedName is not defined.
The scope chain
When code uses a name, the engine looks in the current scope and, if it is not there, in the scope around it, and so on outward until the global scope. That ordered list of scopes is the scope chain. The first match wins, which is exactly what shadowing means: an inner declaration stops the walk before it reaches the outer one.
const rate = 18 function bill(amount) { const outside = rate { const rate = 5 return [rate, amount, outside, typeof Math] } } console.log(bill(100))
Four lookups, four distances
[ 5, 100, 18, 'object' ]
Output (Node 24)
First, outside = rate runs in the function: no rate there, so one scope up
Read it as steps
Each name stops at the first scope that declares it.
The scene follows the lookups in the order they ran. outside was read first, in the function, and found the module-level rate of 18. Inside the block the inner rate of 5 hid it, so the result array holds both: [5, 100, 18, 'object']. Each lookup starts from the scope where the name is used, and Math had to climb all the way to the global scope. A name declared nowhere runs off the end of the chain and throws a ReferenceError, as undefinedName did in the previous run. The scope chain is fixed by where the code is written, not by where a function is called, and that is the root of closures, the next lesson.
Part 5 · Closures
Functions that remember
A closure is a function together with the variables from the scope where it was created. A function keeps access to those variables even after the outer function has returned. This works because of the scope chain from the last lesson: the inner function's chain includes the outer scope, and the engine keeps that scope alive as long as something can reach it.
function makeCounter(start = 0) { let count = start return { inc: () => ++count, get: () => count, } } const a = makeCounter() const b = makeCounter(10) a.inc() a.inc() b.inc() console.log(a.get(), b.get(), a.count) function once(fn) { let done = false let result return (...args) => { if (!done) { done = true result = fn(...args) } return result } } const init = once(() => { console.log('initialising'); return 42 }) console.log(init(), init())
Private state and a run-once wrapper
2 11 undefined initialising 42 42
Output (Node 24)
Each call to makeCounter creates a new count variable, shared by the two functions it returns and invisible to everything else. The two counters are independent: a reached 2 and b reached 11, and a.count is undefined, since no property by that name exists. This is private state without classes. The once wrapper uses the same idea to remember whether it has run, which is why initialising printed a single time.
Closures in loops
The most common closure puzzle is a loop that creates functions. With var, the whole loop shares one variable, so every function sees its final value. With let, each iteration gets a fresh binding, so each function keeps its own.
const fns = [] for (var i = 0; i < 3; i++) fns.push(() => i) console.log(fns.map((f) => f())) const fns2 = [] for (let j = 0; j < 3; j++) fns2.push(() => j) console.log(fns2.map((f) => f())) const fns3 = [] for (var k = 0; k < 3; k++) { fns3.push(((n) => () => n)(k)) } console.log(fns3.map((f) => f())) const timers = [] for (var m = 0; m < 3; m++) { setTimeout(() => timers.push(m), 0) } setTimeout(() => console.log('var timers', timers), 5)
The same loop with var and with let
[ 3, 3, 3 ] [ 0, 1, 2 ] [ 0, 1, 2 ] var timers [ 3, 3, 3 ]
Output (Node 24)
The first line prints [ 3, 3, 3 ]: all three arrow functions read the same i, which was 3 when the loop ended. The second prints [ 0, 1, 2 ] with let. The third shows the pre-let fix, an immediately called function that copies the value into its own scope. The timers case is the same bug in the form people actually meet: three callbacks scheduled in a var loop all pushed 3.
A practical closure: memoising
Closures are how a function carries a private cache. A memoised function stores the result for each input and returns the stored result when the same input comes again. The cache lives in the scope of the wrapper, so no outside code can corrupt it.
function memoize(fn) { const cache = new Map() return (n) => { if (cache.has(n)) return cache.get(n) const value = fn(n) cache.set(n, value) return value } } let calls = 0 const gst = memoize((paise) => { calls += 1 return Math.round(paise * 0.18) }) console.log(gst(100000), gst(100000), gst(250000), calls)
A cache held in a closure
18000 18000 45000 2
Output (Node 24)
The wrapped function computes 18 per cent of an amount in paise. It was called three times, with two distinct inputs, and the counter shows it ran only twice. The cache grows as long as the wrapper lives, so a memoiser over unbounded input needs a limit. The same property applies to every closure: whatever it captures stays in memory while the function can be reached, including large arrays you meant to discard.
Captured variables and stale values
A closure captures the variable, not its value at the time. If the variable changes later, the closure sees the change. Capturing a value instead requires copying it into a new const when the function is made.
function makeTicker() { let n = 0 const snapshot = n return { step() { n += 1 }, stale: () => snapshot, fresh: () => n, } } const t = makeTicker() t.step() t.step() console.log(t.stale(), t.fresh()) let theme = 'light' const readThemeNow = theme const readThemeLater = () => theme theme = 'dark' console.log(readThemeNow, readThemeLater())
Capturing a variable versus a copy
0 2 light dark
Output (Node 24)
Here, readThemeNow holds the string copied while theme was "light", and readThemeLater reads the variable at call time, so it printed "dark". The stale function in the ticker returned the copy taken at creation, 0, while fresh read the live count, 2. A stale closure is a function that holds an old copy of something that has since changed. It shows up in event handlers and timers set up once but meant to see updated state, and the fix is to read the current variable, or to set the handler up again when the value changes.
Why does a var loop that pushes () => i give [3, 3, 3]?
- All three functions share one variable
i, and its value is 3 when the loop ends. - With
let, each iteration gets its own binding, giving[0, 1, 2].
Where does a closure keep its private variables?
- In the scope where it was created. The scope stays alive as long as the function can be reached, and no outside code can name those variables.
What is a stale closure?
- A function holding an old copy of a value that changed afterwards, such as a callback set up once with a copied
const. - Read the live variable, or recreate the function when the value changes.
Part 6 · Module scope
A file is a scope
An ES module, a file loaded with import and export (.mjs in Node, or type="module" in a page), has its own top-level scope. A var or function at the top of a module does not become a property of the global object, so files cannot clash by accident. Modules always run in strict mode, which is why adding a property to a string threw in the first lesson instead of failing silently.
Several classic features are missing or changed at module level. Top-level this is undefined, and in Node module and require do not exist in an ES module. The three files below print the facts from one run of node main.mjs. The first holds shared state, and the other two import it.
export let count = 0 export function inc() { count += 1 } console.log('counter.mjs evaluated')
counter.mjs: one exported binding and a function
import { count, inc } from './counter.mjs' console.log('a sees', count) inc() console.log('a after inc', count) try { count = 99 } catch (e) { console.log(e.constructor.name + ': ' + e.message) }
a.mjs: reads, calls and tries to assign
import { count, inc } from './counter.mjs' import './a.mjs' console.log('main sees', count) inc() console.log('main after inc', count) console.log(typeof this, typeof module, typeof require) console.log(import.meta.url.endsWith('main.mjs'))
main.mjs: the entry file
Live bindings
An import does not copy a value. It creates a live binding, a read-only view of the variable inside the exporting module. When counter.mjs runs count += 1, every importer sees the new number on its next read. The importing side cannot assign to it.
counter.mjs evaluated a sees 0 a after inc 1 TypeError: Assignment to constant variable. main sees 1 main after inc 2 undefined undefined undefined true
Output (Node 24)
Read the output as a timeline. The counter module runs once, before the importers. a.mjs read 0, called inc() and then read 1. Its assignment count = 99 failed with TypeError: Assignment to constant variable., the same message as a const. Then main.mjs, a different file, saw 1, which proves the state is shared. The last line shows undefined undefined undefined for typeof this, typeof module and typeof require.
Contrast with CommonJS
The older Node module system, CommonJS, works differently. A file builds an object and assigns it to module.exports, and require returns that object. Exporting { count, inc } copies the current value of count into the object at that moment, so later changes are not seen.
let count = 0 function inc() { count += 1 } module.exports = { count, inc } console.log('c.cjs evaluated')
c.cjs: exports a copy of count
const mod = require('./c.cjs') const { count, inc } = require('./c.cjs') inc() console.log(count, mod.count)
useCjs.cjs: calls inc, then reads count
c.cjs evaluated 0 0
Output (Node 24)
After inc() ran, both the destructured count and mod.count still read 0. Reading through mod.count did not help, because the exported object holds a copy made when the file finished. An ES module import would have printed 1. When you move code between the two systems, expect this difference.
Evaluated once per URL
The engine keeps a map from each module's resolved URL to its instance. The first import of a URL fetches and runs the file; later imports of the same URL reuse the result. That is why counter.mjs evaluated printed once, although two files imported it. It also makes a module a natural place for a singleton, such as a configuration object or a cache.
A different URL is a different module, even for the same file. In the run below, adding a query string created a second instance with its own count.
const first = await import('./counter.mjs') const same = await import('./counter.mjs') const other = await import('./counter.mjs?copy=2') console.log(first === same, first === other) first.inc() console.log(first.count, other.count)
Same file, two URLs
counter.mjs evaluated counter.mjs evaluated true false 1 0
Output (Node 24)
The output starts with two counter.mjs evaluated lines, one per URL. first === same is true, and first === other is false. After first.inc(), the first instance reads 1 while the second still reads 0. In a browser the URL decides identity in the same way, so one file served under two addresses would run twice.
Is a top-level var in an ES module a property of the global object?
- No. A module has its own scope. Module code is strict, and top-level
thisisundefined.
What is a live binding?
- An imported name that reads the exporting module's variable directly, so it sees later changes. The importer cannot assign to it.
How many times does a module file run if two files import it, and when does it run again?
- Once per resolved URL. A different URL, such as one with a query string, creates a second instance with its own state.
All chapters · Previous: The Frontend System Design Interview