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
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.
โ
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
โ 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.
โ
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
๐ 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!
Top comments (0)