These are the notes for JavaScript Coding Questions, episode 15, interview and placement practice for people who finished the SyntaxPilot JavaScript course. We move from strings to objects, with three questions every JavaScript interview loves: make a deep copy of an object, check whether two objects are deeply equal, and count every key at every level. On the way: why the popular JSON trick quietly breaks your data, what structuredClone does, and why typeof null is "object".
Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.
Every program was run with Node.js 24 (node main.js), the SyntaxPilot compiler's JavaScript command, and every output below is real. Plain modern JavaScript, no packages.
Q1: Make a deep copy of an object
Problem. Copy an object so that changing the copy, at any level, never changes the original.
{ id: 7, items: ["chai", "samosa"], address: { city: "Pune" }, placed: new Date("2026-11-10T09:30:00Z") }
Real life: editing a copy of an order in a cart, an undo history, test data.
Think out loud
- Values inside can be numbers and strings (primitives), objects, arrays, dates,
undefined, functions. - Edge cases: nested objects, arrays,
Date,undefined, an object that points to itself (a cycle).
Attempt 1 and 2: assignment and spread
const order = { id: 7, items: ["chai", "samosa"], address: { city: "Pune" } };
const copy = order;
copy.id = 8;
console.log(order.id);
const copy2 = { ...order };
copy2.id = 9;
copy2.address.city = "Delhi";
console.log(order.id, order.address.city);
8
8 Delhi
- A variable holds a reference to an object (where it lives in memory), not the object.
copy = ordercopies the reference: one object, two names. - Spread
{ ...order }makes a new outer object but copies each value as it is.addressholds a reference, so both objects share the same address object. That is a shallow copy: only the top level is new.Object.assign({}, order)and[...array]are shallow too.
Real life: telling a friend where your project folder is (reference) vs photocopying only the top page (shallow) vs photocopying every page in every sub-folder (deep).
Attempt 3: the JSON trick
const order = {
id: 7, placed: new Date("2026-11-10T09:30:00Z"),
note: undefined, total: NaN, tag: () => "veg",
};
const copy = JSON.parse(JSON.stringify(order));
console.log(copy);
console.log(typeof copy.placed);
{ id: 7, placed: '2026-11-10T09:30:00.000Z', total: null }
string
JSON is a text format with only strings, numbers, booleans, null, arrays and plain objects. So stringify writes the date as text (it never becomes a Date again), drops keys whose value is undefined or a function, and writes NaN and Infinity as null. Map and Set become {}. A cycle throws (below).
Attempt 4: your own recursive clone
Recursion: a function that calls itself on a smaller part of the problem (here, each value inside).
function deepClone(v) {
if (v === null || typeof v !== "object") return v;
if (v instanceof Date) return new Date(v);
if (Array.isArray(v)) return v.map(deepClone);
const out = {};
for (const k of Object.keys(v)) out[k] = deepClone(v[k]);
return out;
}
const order = { id: 7, items: ["chai", "samosa"], address: { city: "Pune" },
placed: new Date("2026-11-10T09:30:00Z"), note: undefined };
const copy = deepClone(order);
copy.address.city = "Delhi";
copy.items.push("jalebi");
console.log(order.address.city, order.items);
console.log(copy.placed instanceof Date, "note" in copy);
const a = { name: "a" };
a.self = a;
deepClone(a);
Pune [ 'chai', 'samosa' ]
true true
main.js:6
for (const k of Object.keys(v)) out[k] = deepClone(v[k]);
^
RangeError: Maximum call stack size exceeded
(The exact line in the first lines of the stack trace can differ between runs: the stack can fill up inside Object.keys or inside instanceof.) The original is untouched, the date is still a Date, note is kept. But a.self = a is a circular reference: cloning a clones a.self, which is a again, forever, until the call stack (the list of function calls still running) is full. JSON fails on it too:
const a = { name: "a" };
a.self = a;
JSON.stringify(a);
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Object'
--- property 'self' closes the circle
Fix: remember what is already copied
function deepClone(v, seen = new Map()) {
if (v === null || typeof v !== "object") return v;
if (v instanceof Date) return new Date(v);
if (seen.has(v)) return seen.get(v);
const out = Array.isArray(v) ? [] : {};
seen.set(v, out);
for (const k of Object.keys(v)) out[k] = deepClone(v[k], seen);
return out;
}
const a = { name: "a", tags: ["x"] };
a.self = a;
const b = deepClone(a);
console.log(b.self === b, b.self === a, Array.isArray(b.tags));
true false true
The Map goes from each original object to its copy. The copy is stored before its keys are filled, so a cycle finds it.
The built-in: structuredClone
const order = { id: 7, items: ["chai"], placed: new Date("2026-11-10T09:30:00Z"),
note: undefined, stock: new Map([["chai", 3]]) };
order.self = order;
const copy = structuredClone(order);
copy.items.push("vada");
console.log(order.items, copy.items);
console.log(copy.placed instanceof Date, copy.stock.get("chai"), copy.self === copy);
structuredClone({ tag: () => "veg" });
[ 'chai' ] [ 'chai', 'vada' ]
true 3 true
node:internal/worker/js_transferable:127
const serializedData = nativeStructuredClone(value, idlOptions);
^
DOMException [DataCloneError]: () => "veg" could not be cloned.
structuredClone (in Node.js 17+ and every modern browser) copies dates, Map, Set, arrays, undefined and cycles. It copies data, not behaviour: functions (and DOM nodes) throw DataCloneError, loudly, instead of silently disappearing like in JSON. Class instances come back as plain objects.
Complexity: every value is visited once: O(n) time and O(n) space, where n is the number of values inside.
Q2: Are two objects deeply equal?
Problem. Same keys, same values at every level; key order does not matter.
{ x: 1, y: 2 } vs { y: 2, x: 1 } → true
{ a: [1, 2] } vs { a: [1, 2] } → true
{ a: 1 } vs { a: 1, b: 2 } → false
{ v: NaN } vs { v: NaN } → true
null vs { a: 1 } → false
[1] vs { 0: 1 } → false
Real life: before saving a settings form, check whether the user really changed anything.
The obvious attempts: === and JSON strings
const a = { name: "Asha", marks: { maths: 90 } };
const b = { name: "Asha", marks: { maths: 90 } };
console.log(a === b);
const same = (x, y) => JSON.stringify(x) === JSON.stringify(y);
console.log(same(a, b));
console.log(same({ x: 1, y: 2 }, { y: 2, x: 1 }));
false
true
false
=== on objects compares references: two different objects are never equal. JSON strings follow the key order, so {x, y} and {y, x} differ (and JSON also loses undefined and dates).
A first recursive version, with three bugs
function deepEqual(x, y) {
if (x === y) return true;
if (typeof x !== "object" || typeof y !== "object") return false;
for (const k of Object.keys(x)) {
if (!deepEqual(x[k], y[k])) return false;
}
return true;
}
console.log(deepEqual({ x: 1, y: 2 }, { y: 2, x: 1 }));
console.log(deepEqual({ a: [1, 2] }, { a: [1, 2] }));
console.log(deepEqual({ a: 1 }, { a: 1, b: 2 }));
console.log(deepEqual({ v: NaN }, { v: NaN }));
console.log(deepEqual(null, { a: 1 }));
true
true
true
false
main.js:4
for (const k of Object.keys(x)) {
^
TypeError: Cannot convert undefined or null to object
- Only the keys of
xare checked, so extra keys inyare never seen. NaN === NaNisfalse: NaN is the only value not equal to itself.typeof nullis"object"(a bug from the first version of JavaScript in 1995, kept so old websites don't break), sonullpasses the object check andObject.keys(null)throws.
Real life: checking two tiffin orders: same number of items, every item on both, open any box inside and check it the same way.
Fix
function deepEqual(x, y) {
if (Object.is(x, y)) return true;
if (typeof x !== "object" || typeof y !== "object") return false;
if (x === null || y === null) return false;
if (Array.isArray(x) !== Array.isArray(y)) return false;
const kx = Object.keys(x), ky = Object.keys(y);
if (kx.length !== ky.length) return false;
for (const k of kx) {
if (!Object.hasOwn(y, k) || !deepEqual(x[k], y[k])) return false;
}
return true;
}
console.log(deepEqual({ x: 1, y: 2 }, { y: 2, x: 1 }));
console.log(deepEqual({ a: [1, 2] }, { a: [1, 2] }));
console.log(deepEqual({ a: 1 }, { a: 1, b: 2 }));
console.log(deepEqual({ v: NaN }, { v: NaN }));
console.log(deepEqual(null, { a: 1 }), deepEqual([1], { 0: 1 }));
console.log(deepEqual({ a: undefined }, { b: undefined }));
true
true
false
true
false false
false
Object.is(x, y)is like===, exceptObject.is(NaN, NaN)istrue(andObject.is(0, -0)isfalse).Object.hasOwn(y, k)checks thatyreally has the keykitself. Without it,{ a: undefined }and{ b: undefined }would look equal (y.aisundefinedtoo).- Same number of keys + every key of
xiny= the same set of keys.
Complexity: O(n) time (each value compared once); O(d) space for the recursion, where d is the nesting depth.
Q3: Count every key, at every level
Problem. Count the keys of an object and of every object inside it. An array is a list, not keys: count the keys of the objects in it, not its positions.
const user = {
name: "Ravi", phone: null,
address: { city: "Pune", pin: "411001" },
orders: [{ id: 1 }, { id: 2 }],
};
// name, phone, address, orders (4) + city, pin (6) + id, id (8) → 8
The obvious attempts
function countKeys(o) {
let n = 0;
for (const k of Object.keys(o)) {
n++;
if (typeof o[k] === "object") n += countKeys(o[k]);
}
return n;
}
console.log(Object.keys(user).length);
console.log(countKeys(user));
4
main.js:8
for (const k of Object.keys(o)) {
^
TypeError: Cannot convert undefined or null to object
Object.keys(user).length counts the top level only. The recursion crashes on phone: null (typeof null is "object" again). Guarding null:
if (typeof o[k] === "object" && o[k] !== null) n += countKeys(o[k]);
4
10
Ten, not eight: an array is an object too, and Object.keys(["x", "y"]) is ["0", "1"], so the positions were counted as keys.
Fix: decide per kind of value, once
function countKeys(v) {
if (v === null || typeof v !== "object") return 0;
if (Array.isArray(v)) return v.reduce((n, item) => n + countKeys(item), 0);
let n = 0;
for (const k of Object.keys(v)) n += 1 + countKeys(v[k]);
return n;
}
console.log(countKeys(user));
console.log(countKeys({}), countKeys([]), countKeys(null), countKeys(42));
8
0 0 0 0
for...in also counts inherited keys
const defaults = { theme: "dark" };
const settings = Object.create(defaults);
settings.lang = "en";
let n = 0;
for (const k in settings) n++;
console.log(n, Object.keys(settings).length, settings.theme);
2 1 dark
Object.create(defaults) makes an object whose prototype (the object it inherits from) is defaults. for...in visits inherited enumerable keys too; Object.keys lists only the object's own keys.
Complexity: O(n) time, O(d) recursion space.
Complexity summary
| Question | Approach | Time | Extra space | Problem |
|---|---|---|---|---|
| Clone | copy = o |
O(1) | O(1) | same object |
| Clone | { ...o } |
O(top-level keys) | O(top-level keys) | shallow |
| Clone | JSON.parse(JSON.stringify(o)) |
O(n) | O(n) | loses Date, undefined, functions; cycles throw |
| Clone | recursive + seen Map |
O(n) | O(n) | functions copied by reference |
| Clone | structuredClone(o) |
O(n) | O(n) | functions throw DataCloneError |
| Equal | === |
O(1) | O(1) | references only |
| Equal | JSON strings | O(n) | O(n) | key order |
| Equal | deepEqual |
O(n) | O(d) | — |
| Count keys | recursive, arrays by items | O(n) | O(d) | — |
Common mistakes (and the exact outputs)
| Mistake | Code | What you see | Why | Fix |
|---|---|---|---|---|
| Assigning an object | const copy = order |
the original changes | a reference is copied | clone |
| Spread as a deep copy | { ...order } |
Delhi in the original |
shallow copy | structuredClone |
| JSON clone | JSON.parse(JSON.stringify(o)) |
typeof placed is string; note gone; NaN → null |
JSON is text only | structuredClone |
| Cycles in recursion | deepClone(a) with a.self = a |
RangeError: Maximum call stack size exceeded |
it never ends | a seen Map |
| Cycles in JSON | JSON.stringify(a) |
TypeError: Converting circular structure to JSON |
JSON can't express cycles | structuredClone |
| Cloning functions | structuredClone({ tag: () => "veg" }) |
DataCloneError: ... could not be cloned. |
it copies data only | keep functions out of data |
=== for equality |
a === b |
false |
compares references | deepEqual |
| JSON for equality | JSON.stringify(x) === JSON.stringify(y) |
false for {x,y}/{y,x} |
key order | deepEqual |
| Keys of one side only | loop over Object.keys(x) |
true for {a:1}/{a:1,b:2} |
extra keys in y unseen |
compare key counts |
=== with NaN |
NaN === NaN |
false |
NaN is never === |
Object.is |
typeof for objects |
typeof v === "object" |
TypeError: Cannot convert undefined or null to object |
typeof null is "object" |
v !== null |
| Arrays as objects | Object.keys(array) |
10 instead of 8 |
indexes "0", "1" are keys |
Array.isArray first |
for...in to count |
for (const k in o) |
2 instead of 1 |
inherited keys | Object.keys |
Mini project: a cart with undo
Keep an undo history of a cart (each step stores a deep copy before changing it) and enable the Save button only when the cart really differs from the saved one.
// Mini project: a cart with undo, and a "save only if something changed" check
function deepEqual(x, y) {
if (Object.is(x, y)) return true;
if (typeof x !== "object" || typeof y !== "object") return false;
if (x === null || y === null) return false;
if (Array.isArray(x) !== Array.isArray(y)) return false;
const kx = Object.keys(x), ky = Object.keys(y);
if (kx.length !== ky.length) return false;
for (const k of kx) {
if (!Object.hasOwn(y, k) || !deepEqual(x[k], y[k])) return false;
}
return true;
}
let cart = { items: [{ name: "chai", qty: 2 }], coupon: null };
const history = [];
function change(fn) {
history.push(structuredClone(cart));
fn(cart);
}
const saved = structuredClone(cart);
change(c => c.items[0].qty++);
change(c => c.items.push({ name: "samosa", qty: 1 }));
console.log(JSON.stringify(cart.items), "changed:", !deepEqual(cart, saved));
cart = history.pop();
cart = history.pop();
console.log(JSON.stringify(cart.items), "changed:", !deepEqual(cart, saved));
[{"name":"chai","qty":3},{"name":"samosa","qty":1}] changed: true
[{"name":"chai","qty":2}] changed: false
With a shallow copy ({ ...cart }) the history would share the same items array, and undo would bring back the already-changed items.
Your turn: deep freeze (solution)
Object.freeze(o) stops adding, removing and changing keys of o, but only at the top level.
Solution
The same recursion as deepClone: freeze every object inside, then the object. Object.isFrozen skips objects already frozen, which also stops cycles.
function deepFreeze(o) {
for (const v of Object.values(o)) {
if (v !== null && typeof v === "object" && !Object.isFrozen(v)) deepFreeze(v);
}
return Object.freeze(o);
}
const shallow = Object.freeze({ db: { port: 5432 } });
shallow.db.port = 1;
console.log(shallow.db.port);
const config = { name: "shop", db: { host: "localhost", port: 5432 }, tags: ["a"] };
deepFreeze(config);
config.db.port = 1;
console.log(config.db.port, Object.isFrozen(config.tags));
try { config.tags.push("b"); } catch (e) { console.log(e.constructor.name + ": " + e.message); }
1
5432 true
TypeError: Cannot add property 1, object is not extensible
Assigning to a frozen object's key is silently ignored outside strict mode (in a "use strict" file or an ES module it throws a TypeError); push on a frozen array always throws.
Practice questions (with solutions)
1. A deepEqual that also compares dates.
Solution
A Date has no own keys (Object.keys(new Date()).length is 0), so our deepEqual says any two dates are equal. Compare their times first.
function deepEqual(x, y) {
if (Object.is(x, y)) return true;
if (x instanceof Date && y instanceof Date) return x.getTime() === y.getTime();
if (typeof x !== "object" || typeof y !== "object") return false;
if (x === null || y === null) return false;
if (Array.isArray(x) !== Array.isArray(y)) return false;
const kx = Object.keys(x), ky = Object.keys(y);
if (kx.length !== ky.length) return false;
for (const k of kx) {
if (!Object.hasOwn(y, k) || !deepEqual(x[k], y[k])) return false;
}
return true;
}
const d1 = new Date("2026-11-10"), d2 = new Date("2026-11-11");
console.log(Object.keys(d1).length);
console.log(deepEqual({ at: d1 }, { at: new Date("2026-11-10") }), deepEqual({ at: d1 }, { at: d2 }));
0
true false
2. The deepest nesting level (a primitive is 0, an object or array is 1 + its deepest value).
Solution
function depth(v) {
if (v === null || typeof v !== "object") return 0;
let max = 0;
for (const x of Object.values(v)) max = Math.max(max, depth(x));
return 1 + max;
}
console.log(depth(42), depth({}), depth({ a: 1 }), depth({ a: { b: { c: 1 } } }), depth([[1], [[2]]]));
0 1 1 3 3
3. List every path, like "address.city".
Solution
function paths(v, prefix = "") {
if (v === null || typeof v !== "object" || Object.keys(v).length === 0) return prefix ? [prefix] : [];
return Object.keys(v).flatMap(k => paths(v[k], prefix ? prefix + "." + k : k));
}
const user = { name: "Ravi", phone: null, address: { city: "Pune", pin: "411001" }, orders: [{ id: 1 }] };
console.log(paths(user));
[ 'name', 'phone', 'address.city', 'address.pin', 'orders.0.id' ]
flatMap maps each key to an array of paths and flattens them into one array.
Quick quiz
1. (From the video.) What does this print?
const a = { n: 1 };
const b = { ...a, n: 2 };
console.log(a.n, b.n, typeof null);
(A) 2 2 object (B) 1 2 null (C) 1 2 object (D) 1 1 undefined
Answer
(C) 1 2 object. Spread makes a new object, so a is untouched; a key written after the spread replaces the copied one; typeof null is "object".
2. What does this print?
const a = { list: [1, 2] };
const b = { ...a };
b.list.push(3);
console.log(a.list, a === b, a.list === b.list);
console.log(JSON.parse(JSON.stringify({ when: new Date(0) })).when);
console.log(typeof [], Array.isArray([]));
Answer
[ 1, 2, 3 ] false true
1970-01-01T00:00:00.000Z
object true
Different outer objects, the same inner array (shallow copy). The date came back as a string (printed without quotes because console.log prints a string's text). typeof an array is "object"; use Array.isArray.
Interview questions
- Shallow vs deep copy? Shallow: a new top-level object sharing nested objects. Deep: new objects at every level.
- Ways to shallow copy?
{ ...o },Object.assign({}, o),[...arr],arr.slice(). - What does
JSON.parse(JSON.stringify(o))lose? Dates (become strings),undefinedand function values (dropped),NaN/Infinity(becomenull),Map/Set(become{}), class prototypes; cycles throw. - What is
structuredClone, and what can't it clone? A built-in deep copy supporting dates, Maps, Sets, typed arrays and cycles; functions and DOM nodes throwDataCloneError. - How do you handle cycles in your own deep clone? A Map (or WeakMap) from originals to copies, filled before recursing.
- Why is
{} === {}false? Objects are compared by reference. - Write
deepEqual.Object.is, null checks, array vs object, equal key counts,Object.hasOwn, recurse. - Why is
typeof null"object"? A bug from JavaScript's first version, kept for backward compatibility. Object.isvs===? Same exceptNaNequalsNaNand0differs from-0.for...invsObject.keys?for...inincludes inherited enumerable keys;Object.keysonly own enumerable string keys.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Primitive | A simple value copied by value: number, string, boolean, null, undefined, bigint, symbol |
7, "chai" |
| Reference | Where an object lives; variables hold this, not the object | copy = order |
| Shallow copy | A new top-level object; nested objects shared | { ...order } |
| Deep copy | New objects at every level | structuredClone(order) |
Spread (...) |
Copies an object's keys or an array's items into a new one | { ...a, n: 2 } |
| JSON | A text format for data | '{"id":7}' |
JSON.stringify / JSON.parse |
Value → JSON text / JSON text → value | JSON.parse("[1]") |
| Recursion | A function calling itself on a smaller part | deepClone(v[k]) |
| Base case | The case that stops recursion | not an object → return it |
| Call stack | The list of function calls still running | full → RangeError |
| Circular reference (cycle) | An object that reaches itself | a.self = a |
RangeError |
A value out of the allowed range; also a full call stack | Maximum call stack size exceeded |
structuredClone |
The built-in deep copy | structuredClone(o) |
DataCloneError |
structuredClone can't copy this value |
a function |
instanceof |
Was this made by that class? | d instanceof Date |
Array.isArray |
Is this an array? | Array.isArray([]) → true |
| Deep equality | Same keys and values at every level | {x:1,y:2} vs {y:2,x:1} |
Object.is |
Same value; NaN equals NaN |
Object.is(NaN, NaN) → true |
NaN |
"Not a Number", never === itself |
0 / 0 |
Object.keys |
An object's own enumerable string keys | Object.keys({a:1}) → ["a"] |
Object.values / Object.entries |
Own values / [key, value] pairs |
Object.values({a:1}) → [1] |
Object.hasOwn |
Does the object itself have this key? | Object.hasOwn({a:1}, "a") |
typeof null |
"object", a historic bug |
always check v !== null |
reduce |
Combine items into one value | [1,2].reduce((n, x) => n + x, 0) |
| Prototype | The object another object inherits from | Object.create(defaults) |
| Inherited key | A key found on the prototype | settings.theme |
for...in |
Loops over own and inherited enumerable keys | for (k in settings) |
Object.freeze |
Stop changes to an object (top level only) | Object.freeze(config) |
| O(d) space | Memory that grows with nesting depth | recursion |
Summary
- Deep clone: assignment copies a reference, spread is shallow, and JSON loses dates,
undefined, functions andNaN, and throws on cycles. Your own recursion needs aseenMap for cycles; in real code usestructuredClone, which copies dates, Maps and cycles and throws on functions. - Deep equal:
===compares references and JSON depends on key order. UseObject.is, check fornull, separate arrays from objects, compare key counts andObject.hasOwn, and recurse. - Count keys:
typeof nullis"object", arrays have index keys, andfor...insees inherited keys. Decide per kind of value once at the top of the function and useObject.keys.
Next episode: Object questions II: invert an object, merge objects deeply, and read a nested value by a path like "a.b.c" with optional chaining.