← Back to JavaScript, page 8

javascript-0150 · Medium mid

Predict the output of these array and object puzzles, such as map with parseInt, holes, key order, and shared references.

Most array and object surprises come from a few rules: callbacks such as map receive extra arguments, arrays can be sparse, array length is writable, integer-like object keys are ordered first, objects and arrays compare by reference, fill and spread copy references and not values, and object keys are always strings or symbols. Name the rule before the output.

Full answer

Go through the puzzles by rule.

Rule 1, callback arguments: map, filter, and forEach call the function with (value, index, array). So ['1', '2', '3'].map(parseInt) calls parseInt('2', 1), where 1 is not a valid radix, and gives [1, NaN, NaN].

Rule 2, sparse arrays: [1, , 3] and new Array(3) have holes. forEach, map, and filter skip holes. delete arr[1] leaves a hole and does not change length. Object.keys skips holes and for...in too, while for...of and the spread syntax visit them as undefined.

Rule 3, length is writable: arr.length = 0 empties the array, and assigning to arr[10] on a short array grows length to 11 and leaves holes. A negative index is just a property: arr[-1] = 'x' does not change length.

Rule 4, key order: for plain objects, integer-like keys come first in ascending order, then string keys in insertion order, then symbols. So { b: 1, 2: 1, a: 1, 1: 1 } lists 1, 2, b, a.

Rule 5, reference comparison: {} === {} and [] === [] are false, and [1] == [1] is false. Two variables are equal only if they point to the same object.

Rule 6, shared references: new Array(3).fill([]) puts the same array in all three slots. Array.from({ length: 3 }, () => []) creates three arrays. Spread { ...obj } and [...arr] copy one level, so nested objects stay shared.

Rule 7, key coercion: object keys are converted to strings, so obj[1] and obj['1'] are the same key, and every object used as a key becomes '[object Object]'. A Map keeps the real key.

Also: the default sort compares as strings, typeof [] is 'object', and Array.isArray is the right check.

javascript
const show = (label, value) => console.log(label.padEnd(28), value);

show("['1','2','3'].map(parseInt)", ['1', '2', '3'].map(parseInt));
show("['1','2','3'].map(Number)", ['1', '2', '3'].map(Number));

const sparse = [1, , 3];
const visited = [];
sparse.forEach((v, i) => visited.push(i));
show('sparse forEach indexes', visited);
show('sparse length, keys', [sparse.length, Object.keys(sparse)]);
show('spread of a sparse array', [...sparse]);
show('map over holes', sparse.map((v) => v * 2));

const arr = [1, 2, 3];
delete arr[1];
show('after delete arr[1]', [arr, arr.length]);
arr.length = 1;
show('after length = 1', arr);
arr[4] = 'x';
show('after arr[4] = "x"', [arr, arr.length]);
arr[-1] = 'neg';
show('negative index', [arr.length, arr[-1]]);

show('key order', Object.keys({ b: 1, 2: 1, a: 1, 1: 1, [Symbol('s')]: 1 }));
show('{} === {}, [] == []', [{} === {}, [] == []]);
show('[1] == 1, [1,2] == "1,2"', [[1] == 1, [1, 2] == '1,2']);

const shared = new Array(3).fill([]);
shared[0].push('x');
show('fill with one array', JSON.stringify(shared));
const separate = Array.from({ length: 3 }, () => []);
separate[0].push('x');
show('Array.from with a factory', JSON.stringify(separate));

const original = { name: 'Asha', tags: ['a'] };
const copy = { ...original };
copy.name = 'Ben';
copy.tags.push('b');
show('shallow copy', [original.name, original.tags]);

const keyObject = {};
const key1 = { id: 1 };
const key2 = { id: 2 };
keyObject[key1] = 'first';
keyObject[key2] = 'second';
show('object keys', [Object.keys(keyObject), keyObject[key1]]);
const map = new Map([[key1, 'first'], [key2, 'second']]);
show('Map keeps real keys', [map.size, map.get(key1)]);
const numbers = { 1: 'a' };
show('obj[1], obj["1"]', [numbers[1], numbers['1']]);

show('[10, 9, 1].sort()', [10, 9, 1].sort());
show('typeof [] and Array.isArray', [typeof [], Array.isArray([])]);
show('Array(3) and Array(3, 4)', [Array(3).length, Array(3, 4)]);
show('[,].length, [,,].length', [[,].length, [, ,].length]);
show('[] + [] and [].length', [[] + [], [].length]);
show('indexOf(NaN), includes(NaN)', [[NaN].indexOf(NaN), [NaN].includes(NaN)]);

Run with Node.js v24.22.1 as js-150.js; two runs gave identical output. Output: ['1','2','3'].map(parseInt) [ 1, NaN, NaN ] ['1','2','3'].map(Number) [ 1, 2, 3 ] sparse forEach indexes [ 0, 2 ] sparse length, keys [ 3, [ '0', '2' ] ] spread of a sparse array [ 1, undefined, 3 ] map over holes [ 2, <1 empty item>, 6 ] after delete arr[1] [ [ 1, <1 empty item>, 3 ], 3 ] after length = 1 [ 1 ] after arr[4] = "x" [ [ 1, <3 empty items>, 'x' ], 5 ] negative index [ 5, 'neg' ] key order [ '1', '2', 'b', 'a' ] {} === {}, [] == [] [ false, false ] [1] == 1, [1,2] == "1,2" [ true, true ] fill with one array [["x"],["x"],["x"]] Array.from with a factory [["x"],[],[]] shallow copy [ 'Asha', [ 'a', 'b' ] ] object keys [ [ '[object Object]' ], 'second' ] Map keeps real keys [ 2, 'first' ] obj[1], obj["1"] [ 'a', 'a' ] [10, 9, 1].sort() [ 1, 10, 9 ] typeof [] and Array.isArray [ 'object', true ] Array(3) and Array(3, 4) [ 3, [ 3, 4 ] ] [,].length, [,,].length [ 1, 2 ] [] + [] and [].length [ '', 0 ] indexOf(NaN), includes(NaN) [ -1, true ]

Key points

  • map passes value, index, and array, so parseInt gets a radix; use unary wrappers.
  • Holes are skipped by forEach, map, and filter; delete leaves a hole; length is writable.
  • Object key order: integer keys ascending, then strings by insertion, then symbols.
  • Objects compare by reference; fill and spread copy references and are shallow.
  • Object keys are strings or symbols; use Map for other key types.

Common mistakes

  • Passing parseInt directly to map.
  • Treating holes as undefined values, and expecting forEach to visit them.
  • Creating a matrix with new Array(n).fill([]).
  • Copying an object with spread and assuming nested data is copied.

Follow-ups

  • How would you create a two-dimensional array of independent rows?
  • Why are integer-like keys ordered first, and does the same hold for a Map?
  • How does the sparse array differ from an array filled with undefined?

Tips

  • Name the rule first, then give the output.
  • Use Array.from with a factory for independent items.
  • Mention Map for non-string keys.