DEV Community

ValPetal Tech Labs
ValPetal Tech Labs

Posted on

Question of the Day #5 [Talk::Overflow]

This post explains a quiz originally shared as a LinkedIn poll.

🔹 The Question

const arr = ['1', '7', '11'];
const result = arr.map(parseInt);
console.log(result);
Enter fullscreen mode Exit fullscreen mode

Hint: Think about how many arguments map passes to its callback, and what parseInt does with a second argument.

🔹 Solution

Correct Answer: B) [1, NaN, 3]

The output is: [1, NaN, 3]

🧠 How this works

This is a classic JavaScript gotcha that catches developers because of a mismatch between what Array.prototype.map provides and what parseInt expects.

The key insight: map() doesn't just pass the element to the callback—it passes three arguments:

  1. The current element
  2. The current index
  3. The entire array

Meanwhile, parseInt(string, radix) accepts:

  1. The string to parse
  2. The radix (base) for parsing (2-36)

When you write arr.map(parseInt), the index gets passed as the radix. This causes unexpected parsing behavior.

🔍 Line-by-line explanation

Let's trace through each iteration:

Iteration 0: parseInt('1', 0, arr)

  • string = '1', radix = 0
  • A radix of 0 (or undefined/omitted) defaults to base 10
  • parseInt('1', 10)1

Iteration 1: parseInt('7', 1, arr)

  • string = '7', radix = 1
  • Base 1 is invalid (radix must be 2-36 or 0)
  • parseInt returns NaN

Iteration 2: parseInt('11', 2, arr)

  • string = '11', radix = 2
  • Base 2 (binary) interprets '11' as 1×2¹ + 1×2⁰ = 3
  • parseInt('11', 2)3

The misleading part: Developers often think arr.map(parseInt) is equivalent to arr.map(x => parseInt(x)). It's not—the former passes extra arguments that change behavior entirely.

🔹 Real-World Impact

This pattern appears in production code when:

  • Quick data transformations: Developers try to convert an array of string numbers to integers with a terse one-liner
  • CSV/API parsing: Reading numeric data from CSV files or API responses and mapping directly through parseInt
  • Form data processing: Converting form field values (which are always strings) to numbers

🔹 The Fix

Always be explicit about what you're passing:

// Option 1: Arrow function wrapper
const result = arr.map(x => parseInt(x, 10));

// Option 2: Number constructor (for simple cases)
const result = arr.map(Number);

// Option 3: Unary plus operator
const result = arr.map(x => +x);
Enter fullscreen mode Exit fullscreen mode

🔹 Key Takeaways

  • Array.prototype.map passes three arguments to its callback: (element, index, array)
  • parseInt interprets its second argument as the radix (number base)
  • Passing a function reference directly to map can cause unintended argument passing
  • Always wrap callbacks when you need to control exactly which arguments are passed
  • This applies to other functions too: ['1', '2'].map(console.log) logs "1" 0 Array(2), not just "1"

Top comments (0)