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)