DEV Community

Ankit chaurasiya
Ankit chaurasiya

Posted on

๐Ÿง  Beware the Leading Zero! Understanding Octal Numbers in JavaScript

When you write let x = 0123; in JavaScript, you might think you're assigning the number 123.
But JavaScript has a sneaky surprise in storeโ€ฆ ๐Ÿ˜…

In this article, weโ€™ll decode what happens when you use leading zeros in JavaScript numbers โ€” and how it can trip up even experienced developers.

๐Ÿ” What Happens with let x = 0123;?
In non-strict mode, numbers that start with a 0 (zero) might be treated as octal (base 8).

let x = 0123;
console.log(x); // Output: 83

Enter fullscreen mode Exit fullscreen mode

Why? Because:

0123 (octal) = 1ร—64 + 2ร—8 + 3ร—1 = 83

๐Ÿคฏ Yep, 0123 is NOT 123. Itโ€™s octal โ€” which confuses the heck out of your logic if you didnโ€™t mean it!

โš ๏ธ Strict Mode Throws an Error
If you use "use strict", JavaScript disallows legacy octal literals:

"use strict";
let x = 0123; // โŒ SyntaxError: Octal literals are not allowed in strict mode.
Enter fullscreen mode Exit fullscreen mode

โœ… The Modern and Safe Way: Use 0o Prefix
To explicitly define octal numbers, use the ES6 octal literal syntax with a 0o prefix:

let x = 0o123;
console.log(x); // 83
Enter fullscreen mode Exit fullscreen mode

โœ‹ Common Mistakes to Watch Out For
โŒ Using invalid digits in octal:

let y = 089; // SyntaxError in non-strict mode too
Octal only allows digits 0โ€“7.
Enter fullscreen mode Exit fullscreen mode

โœ… Always define numeric literals intentionally:

let normal = 123;     // Decimal
let octal = 0o123;    // Octal (equals 83)
let hex = 0x1A;       // Hexadecimal (equals 26)
let binary = 0b1010;  // Binary (equals 10)
๐Ÿ’ก Quick Quiz!
Whatโ€™s the output of this code?

- let a = 010;
- console.log(a);
- A) 10
- B) 8
- C) SyntaxError
- D) 0o10
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ Drop your answer in the comments!

๐Ÿ”š Conclusion
Always be cautious when using leading zeros in JavaScript numbers โ€” they might not mean what you think. Avoid legacy octal literals and use the modern 0o syntax when you really want base-8 values.

Have you ever been bitten by this quirk in production code? ๐Ÿ˜ฌ Let me know below!

๐Ÿ”— Follow me for more JavaScript tips, frontend deep dives, and developer tools!

JavaScript #WebDevelopment #DevTips #Frontend #ES6 #CodingTips #JSQuirks #Octal #Devto

Top comments (0)