JavaScript traps · JavaScript

JavaScript: map(parseInt) = 1, NaN, NaN?!PRO

Watch the video

map passes (value, index) and parseInt reads the index as the base. .map(Number) fixes it.

// ["1","2","3"].map(parseInt) = [1, NaN, NaN] ?!
// map passes (value, index) and parseInt reads the index as the number BASE.
console.log(["1", "2", "3"].map(parseInt));   // [1, NaN, NaN] ?!
// parseInt("1", 0) → 1, parseInt("2", 1) → NaN, parseInt("3", 2) → NaN

console.log(["1", "2", "3"].map(Number));                 // [1, 2, 3] ✓
console.log(["1", "2", "3"].map(s => parseInt(s, 10)));   // [1, 2, 3] ✓
Open code JS6 in Pocket Compiler Download the Pocket Compiler app — free

No app yet? Install it, then open the app and type the code JS6 in Code Library.