In JavaScript, the behavior of ['1', '5', '11'].map(parseInt) can be perplexing. To understand this, let's dive into how **map **and **parseInt **interact.
The map Function
The map function creates a new array by applying a provided function to each element in the array. It passes three arguments to the callback function: the element, the index, and the entire array.
The parseInt Function
The parseInt function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems). Its signature is parseInt(string, radix).
The Interaction
When using parseInt within map, the map function inadvertently passes the index of the element as the second argument to parseInt. This causes unexpected behavior:
For the first element '1' (index 0), parseInt('1', 0) is called. The 0 radix means the base is guessed based on the string's format, defaulting to 10. Result: 1.
For the second element '5' (index 1), parseInt('5', 1) is called. But 1 is not a valid radix, so the result is NaN.
For the third element '11' (index 2), parseInt('11', 2) is called. Here, 2 means binary. The valid binary digits are 1, resulting in 3 (since 1*2^1 + 1*2^0 = 3).
The Solution
To ensure parseInt only receives the element, you can use an arrow function or another method to explicitly handle the conversion:
console.log(['1', '5', '11'].map(num => parseInt(num))); // [1, 5, 11]
Or use the Number constructor:
console.log(['1', '5', '11'].map(Number)); // [1, 5, 11]
Understanding this interaction highlights the importance of knowing how JavaScript functions interact and ensuring the correct parameters are passed to avoid unexpected results.
That's all for today.
And also, share your favourite web dev resources to help the beginners here!
Connect with me:@ LinkedIn and checkout my Portfolio.
Explore my YouTube Channel! If you find it useful.
Please give my GitHub Projects a star ⭐️
Thanks for 25659! 🤗