JavaScript’s Array.prototype.map() is simple on the surface yet surprisingly deep once you inspect how callbacks, types, coercion, and encoding work under the hood. One of the most infamous examples — [1,2,3].map(parseInt) — looks harmless but produces confusing output that often appears in interviews.
This guide breaks everything down clearly: how map() really works, why parseInt misbehaves, how NaN is detected, how wrapper objects make "text".length possible, and why emoji “length” is unintuitive. Each section includes modern examples and best-practice patterns.
1. How map() Actually Works
1.1 Syntax and Basic Behavior
map() creates a brand-new array using your callback’s return values. The original array is never modified.
const transformed = sourceList.map(
(itemValue, itemPosition, originalList) => {
return /* computed value */;
},
optionalThisArgument
);
1.2 Practical Examples
Example 1: Transforming numbers
const baseNumbers = [2, 5, 10];
const doubledValues = baseNumbers.map(num => num * 2);
console.log(doubledValues); // [4, 10, 20]
Example 2: Mapping object properties
const studentRecords = [
{ nickname: 'Lara' },
{ nickname: 'Tomas' }
];
const extractedNames = studentRecords.map(entry => entry.nickname);
Example 3: Using map() on array-like structures
const pseudoArray = { 0: 'x', 1: 'y', length: 2 };
const uppercased = Array.prototype.map.call(pseudoArray, val => val.toUpperCase());
1.3 Sparse Arrays and Missing Elements
const weird = [7, , 21];
const output = weird.map(unit => unit * 3);
2. Understanding parseInt() — and Why It Breaks with map()
2.1 Parsing Rules
parseInt('0xA', 16); // 10
parseInt('10', 8); // 8
parseInt('7.8', 10); // 7
parseInt('xy', 10); // NaN
3. Why [1, 2, 3].map(parseInt) Gives [1, NaN, NaN]
3.1 The Output
console.log([1, 2, 3].map(parseInt)); // [1, NaN, NaN]
3.2 The Real Reason
map() passes (value, index, array) while parseInt expects (string, radix).
3.3 Correct Solutions
['1', '2', '3'].map(str => parseInt(str, 10));
['1', '2', '3'].map(Number);
4. Special Numeric Values: NaN and Infinity
4.1 Properties of NaN
Number.isNaN(value);
isNaN(value);
5. Wrapper Objects
"hello".length;
6. UTF-16, Unicode, and Emoji Length Issues
Array.from("👩💻").length;
7. Interviewer Expectations
- Higher-order function comprehension
- Callback mechanics
- Debugging ability
- Understanding coercion and Unicode
Conclusion
map() touches many deeper JS concepts, from number parsing to Unicode. Mastering these details helps you write safer, clearer, more predictable code — and ace interview challenges.
Top comments (0)