Post: WTFJS?
WTFJS?
There’s a lot of interesting content in WTFJS. It is a project that started with a keynote presented by Brian Leroux in 2012, collecting a list of bizarre aspects of JS. These mostly consist of non-intuitive results due to implicit operations like JS’s automatic type conversion. Most examples make you wonder if such things could actually happen, but many are indeed plausible scenarios.
For instance, there are issues caused by parseInt
.
parseInt
parseInt("fck"); // -> NaN parseInt("fck", 16); // -> 15
💡 Explanation: This occurs because
parseInt
continues to parse the string character by character until it reaches an unknown character. In ‘f*ck’, f represents 15 in hexadecimal.parseInt(null, 24); // -> 23
💡 Explanation: Trying to convert
null
to the string “null”. Since there are no numbers to convert for bases 0 to 23, it returns NaN. At base 24, “n”, the 14th letter, gets added to the numeral system. By 31, “u”, the 21st letter is included, allowing the entire string to be decoded. At 37, there are no more valid sets of numbers to generate, thus returning NaN. — “parseInt(null, 24) === 23… wait, what?” on StackOverflow
parseInt(0.000001); // -> 0 parseInt(0.0000001); // -> 1 parseInt(1 / 1999999); // -> 5
💡 Explanation:
parseInt
takes a string argument and returns an integer of the specified radix.parseInt
also strips everything in the string parameter that is not the first non-digit, including numbers. 0.000001 turns into the string “0.000001”, andparseInt
returns 0. 0.0000001 transforms into the string “1e-7”, soparseInt
returns 1. 1/1999999 is interpreted as 5.00000250000125e-7, andparseInt
returns 5.
Summary
In summary, parseInt
behaves as follows:
- It applies
toString
to every input. Even to Numbers! - If there is nothing to parse, it throws an error. However, if there’s something to parse, it parses as much as it can and pretends everything’s normal, always parsing from the beginning.
- If the radix is not specified, and if ES5 is supported, it defaults to decimal 10, but if not supported, it processes based on the input string.
Thus, when using parseInt
, it’s best to follow these guidelines:
- Verify that the input is actually a string.
- Always specify the radix.
- Make sure the string consists only of characters valid for the radix you’re parsing (consider using regular expressions for validation).