0:00 / 0:00
I ❤ JavaScript: Weird parseInt
Styled JavaScript
1.7K subscribers • 7 videos on Hallway
- Recommended by 2 people: 2 in engineering communities.
Beginner. No background in the topic needed.
1.1K views8 years ago2 recommendations
Programming languagesJavaScript
An explanation of the behavior of the parseInt function in JavaScript and how it handles non-numeric characters.
Hi, let's talk today about a parseInt function in JavaScript. I'm Anatol and you're watching the Good Parts of the FrontEnd development. 1) ecma-international.org/ecma-262/5.1/#sec-15.1.2.2 According to ECMAScript Specification the parseInt function produces an integer value dictated by interpretation of the contents of the string argument according to the specified radix. Therefore, "f" is equal to 15 based on the radix-16. But the very next "*" will be out of range, hence parseInt ignores any character that cannot be interpreted as part of the notation and it stops processing and ignores the rest of the string. Consequently, the result is just "15". parseInt('f*ck'); // NaN parseInt('f*ck', 16); // 15 As you might know, the unary plus operator is a just a shorthand for pasrseInt operator. However you cannot do this trick with it, because a unary plus has no radix. +('f*ck') You can play the same trick on "null". ParseInt function converts "null" to a string. For radixes is equal to 24 you have a set consisting of: numbers from 0 to 9 and letters from "a" to "n". "n" is the 14th letter or 23rd element of radix 24. parseInt(null); // NaN parseInt(null, 24); // 23 You can solve the following puzzle in the same way: "parseInt(1 / 0, 19)". "1/0" evaluates to Infinity in JavaScript according IEEE 754 standard. Infinity, in its turn, is converted into a "Infinity" string. Then parseInt function takes "I" of base 19 and converts it into a base 10, which becomes 18. The next character "n" is not present in base 19, so the function stops processing and returns the result, that is "18". parseInt(1 / 0, 19); // 18 That's it. So easy. If you like this video give it "thumbs up". Thanks for watching and stay curious. Subscribe to the channel: youtube.com/c/AnatolMerezhanyi?sub_confirmation=1 Watch other episodes: youtube.com/playlist?list=PLEZfD_aygfgJVaxYUqojEGPjgM6lXzIQ7 Follow on Twitter: twitter.com/e1r0nd_crg Used: looperman.com: Rosita Lofi Beat by Fanto8BC, Progress by nightingale, Chiptune Melody by L0neW0lf, Film Noir by LankFrampard, Russian Boogie by nightingale