Denis Kirevby Denis Kirev

Top 10 JavaScript Quirks Every Developer Should Know

Understanding and mastering the most common JavaScript quirks and gotchas.

3 min read
JAVASCRIPTCOREGUIDE
Image

This article explores 10 quirks in JavaScript that can surprise developers and how to handle them effectively.


1. 0.1 + 0.2 !== 0.3

JavaScript uses the IEEE 754 standard for floating-point arithmetic, which can cause precision issues.

console.log(0.1 + 0.2) // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3) // false

// Fix with rounding
console.log(Number((0.1 + 0.2).toFixed(10)) === 0.3) // true

2. NaN is not equal to itself

NaN (Not-a-Number) has a unique behavior: it is not equal to itself.

console.log(NaN === NaN) // false
console.log(Object.is(NaN, NaN)) // true

// Check for NaN
console.log(Number.isNaN(NaN)) // true

3. typeof null is "object"

A well-known bug in JavaScript that persists for backward compatibility.

console.log(typeof null) // "object"

// Explicitly check for null
console.log(null === null) // true

4. Empty arrays are equal to empty strings

Loose comparisons in JavaScript can lead to surprising results.

console.log([] == '') // true
console.log([1, 2] == '1,2') // true

// Use strict comparison
console.log([] === '') // false

5. Bitwise operations convert to 32-bit integers

JavaScript converts numbers to 32-bit signed integers during bitwise operations.

console.log(2147483647 | 0) // 2147483647
console.log(2147483648 | 0) // -2147483648 (overflow)

6. [] + [] returns an empty string

Adding arrays together converts them into strings.

console.log([] + []) // ""
console.log([] + {}) // "[object Object]"
console.log({} + []) // 0 (in some environments)

7. true converts to 1, false to 0

Boolean values are coerced into numbers during arithmetic operations.

console.log(true + true) // 2
console.log(true - false) // 1

8. parseInt stops at invalid characters

parseInt processes a string until it encounters an invalid character.

console.log(parseInt('10.5')) // 10
console.log(parseFloat('10.5')) // 10.5

9. Empty strings equal 0 in loose comparison

Loose comparison can lead to unexpected results when comparing empty strings.

console.log('' == 0) // true
console.log('' === 0) // false

10. Functions accept extra arguments

JavaScript functions do not enforce the number of arguments passed.

function add(a, b) {
  return a + b
}
console.log(add(1, 2, 3)) // 3

// Use default parameters
function add(a, b = 0) {
  return a + b
}
console.log(add(1)) // 1

Conclusion

Understanding JavaScript quirks can help you write more predictable and maintainable code. Which one surprised you the most? Share your thoughts in the comments!


Table of Contents


Last updated: January 25, 2025