JavaScript Secrets: Weird Coding Tricks & Hidden Bugs
Discover strange but powerful JavaScript coding tricks that look like bugs—but actually work. Improve your coding skills with these secret developer hacks.
1. true + false = 1Â (Boolean Arithmetic)
console.log(true + false); // 1
Why?
- JavaScript converts booleans to numbers in math operations
true
 becomesÂ1
false
 becomesÂ0
- SoÂ
1 + 0 = 1
Practical Example
Instead of:
let count = 0;
if (isAdmin) count++;
if (isModerator) count++;
You could write your code like below:
const count = isAdmin + isModerator;
NOTE:
Though it works but difficult to read, it can be confusing. Use cautiously.
2. [] + {} = “[object Object]” (Strange Concatenation)
console.log([] + {}); // "[object Object]"
console.log({} + []); // 0 (in some browsers)
Why?
Expression: [] + {}
Conversion: []
 → ""
, {}
 → "[object Object]"
Result: “” + “[object Object]”
Expression: {} + []
Conversion: {}
 as empty block, +[]
 → 0
Result: 0
3. 0.1 + 0.2 !== 0.3 (Floating-Point Puzzle)
console.log(0.1 + 0.2); // 0.30000000000000004
Why?
Computers use binary floating-point which can’t perfectly represent decimals.
Solutions:
Method: toFixed()
Example: (0.1 + 0.2).toFixed(1)
Method: Integer math
Example: (0.1*10 + 0.2*10)/10
Tips:
Use decimal.js
 for financial calculations.
4. “b” + “a” + +”a” + “a” = “baNaNa”
console.log("b" + "a" + +"a" + "a"); // "baNaNa"
Why?
"b" + "a"
 →Â"ba"
+"a"
 →ÂNaN
 (failed number conversion)"ba" + NaN + "a"
 →Â"baNaNa"
Note:
Funny!! So never use it in production, right?
5. (!+[]+[]+![]).length === 9
console.log((!+[]+[]+![]).length); // 9
Why?
+[]
 →Â0
!0
 →Âtrue
true + []
 →Â"true"
![]
 →Âfalse
"true" + "false"
 →Â"truefalse"
 (length 9)
Warning:
This is code is meaningless!
6. null > 0, null == 0, null >= 0 (Weird Comparisons)
console.log(null > 0); // false
console.log(null == 0); // false
console.log(null >= 0); // true
Why?
>
 andÂ<
 convertÂnull
 toÂ0
==
 doesn’t convertÂnull
 except withÂundefined
>=
 usesÂ>
 logic
Tip:
7. “2” + “2” – “2” = 20 (String vs Number Math)
console.log("2" + "2" - "2"); // 20
Why?
"2" + "2"
 →Â"22"
 (string concatenation)"22" - "2"
 →Â20
 (subtraction forces number conversion)
Tip:
Should You Use These Tricks?
When They’re Helpful
- Debugging type coercion issues
- Understanding how JavaScript works
When to Avoid
- Production code
- Team projects
- Anywhere readability matters
Pro Tip:
Configure ESLint with:
{
"rules": {
"no-implicit-coercion": "error",
"eqeqeq": "error"
}
}
Best Practices:
- Always useÂ
===
 overÂ==
- Explicitly convert types when needed
- Add comments when using non-obvious behavior
JavaScript Quiz:
- What doesÂ
typeof NaN
 return?- “number”
- “NaN”
- “undefined”
- What isÂ
[] == ![]
?- trueÂ
- false
- Error
"5" - - "2"
 equals:- 3
- “3”
- 7
Math.min() > Math.max()
 returns:- true
- false
- Error
!!"false" === !!"true"
 is:- true
- false
- Error
Answers (JavaScript Quiz)
- a
- a
- c
- a
- a