JavaScript parseInt() function quirks in coding interview

🤯 𝐓𝐡𝐞 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧 𝐓𝐡𝐚𝐭 𝐓𝐮𝐫𝐧𝐬 𝟏𝟎 𝐢𝐧𝐭𝐨 𝐍𝐚𝐍 ['1', '10', '100'].map(parseInt) If you are like most developers, your intuition probably tells you the output will be [𝟏, 𝟏𝟎, 𝟏𝟎𝟎]. It looks like it should just convert the strings to numbers, right? But if you run it, JavaScript gives you a shock: [𝟏, 𝐍𝐚𝐍, 𝟒]. Why does this happen? The confusion stems from how 𝐦𝐚𝐩 and 𝐩𝐚𝐫𝐬𝐞𝐈𝐧𝐭 interact. When you use map(parseInt), the map function passes three arguments to the callback: the element, the index, and the array. However, parseInt accepts two arguments: the string to parse and the 𝐫𝐚𝐝𝐢𝐱 (the number system base). Here is the step-by-step breakdown of what really happens: 1️⃣ 𝐈𝐭𝐞𝐫𝐚𝐭𝐢𝐨𝐧 𝟏: parseInt('1', 0) The index is 0. For parseInt, a radix of 0 defaults to the decimal number system. Result: 𝟏 2️⃣ 𝐈𝐭𝐞𝐫𝐚𝐭𝐢𝐨𝐧 𝟐: parseInt('10', 1) The index is 1. A radix of 1 is an 𝐢𝐧𝐯𝐚𝐥𝐢𝐝 𝐫𝐚𝐧𝐠𝐞 for number systems (which typically start at 2). Because the base is invalid, the function fails. Result: 𝐍𝐚𝐍 3️⃣ 𝐈𝐭𝐞𝐫𝐚𝐭𝐢𝐨𝐧 𝟑: parseInt('100', 2) The index is 2. parseInt treats the number 2 as the binary number system. In binary, "100" equals the decimal number 4. Result: 𝟒 It’s a classic example of why understanding the arguments your functions accept—and what callbacks provide—is crucial in 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭. #JavaScript #CodingInterview #WebDevelopment #ProgrammingHumor #TechTips

To view or add a comment, sign in

Explore content categories