JavaScript: Surprise Octal Numbers

Photo by Francesco Dondi on Unsplash

In a recent problem I was working on, I was parsing the individual ones and zeroes representing the bits of a binary number, and assigning them to variables. I quickly ran into something I didn’t expect.

When I tried to assign some numbers to a variable, it would be saved as a completely different number. What I found was when JavaScript encounters a number prefixed with 0, and that number doesn’t contain an 8 or a 9, it will be interpreted as an Octal, or a Base-8 number. That is, a number system that is represented by the numbers 0–7.

While prefixing zeros is not something you should be doing, especially when declaring a variable, this automatic assignment may cause you a quick headache as well someday. Luckily, this type of integer assignment is officially discouraged. As of ECMAScript 5, this type of integer assignment throws an error in strict mode.

If you do want to declare a variable as a specific base number, ECMAScript 6 offered a smarter solution for that. Now you can prefix numbers to indicate what type of number they represent.

Note however that the variable will still be the base-10 representation of that number. To display the other base versions of a number you can use the toString() method. It accepts a radix, a base number to convert to from 2–36, as an argument. Keep in mind however that it’s still just a string representation, and not a JavaScript number.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jeremy Wood

Jeremy Wood

I’m a full stack engineer who loves to learn, solve problems, and fix things! When I’m not working on my code, you’ll usually find me working on my motorcycles.