7 JavaScript Type Coercion Pitfalls You Must Avoid
This article explores seven common JavaScript type‑coercion pitfalls—including number‑string, boolean, null/undefined, object, array, multiple operand, and NaN comparisons—showing surprising results and providing code examples to help developers avoid subtle bugs in real‑world applications.
Type conversion is one of the most error‑prone features in JavaScript, especially the implicit conversion performed by the double‑equals (==) operator. This article examines common pitfalls and shows how to avoid them in real code.
Pitfall 1: Comparing Numbers and Strings
When a number is compared with a string, JavaScript tries to convert the string to a number. If the string is not a valid numeric representation, the result can be surprising.
console.log(1 == '1') // true
console.log(1 == '1.0') // true
console.log(1 == '01') // true
console.log(0 == '') // true
// more extreme examples
console.log(999 == '999fitness') // false
console.log(0 == '0.0000') // truePitfall 2: Boolean Conversion
Booleans are converted to numbers before comparison (true → 1, false → 0).
console.log(true == 1) // true
console.log(false == 0) // true
console.log(true == '1') // true
console.log(false == '') // true
// confusing cases
console.log(false == '0') // true
console.log(true == '2') // false
console.log(true == ['1']) // true 🤯Pitfall 3: null and undefined
The comparison null == undefined is a special rule; when used in relational comparisons, null is converted to the number 0.
Pitfall 4: Object vs. Primitive Comparison
When an object is compared with a primitive, JavaScript calls the object's valueOf() or toString() method.
Pitfall 5: Array Edge Cases
Empty arrays and arrays have their own conversion rules that can be confusing.
Pitfall 6: Multiple Type Conversions
When several operands are involved, the conversion rules become more complex.
Pitfall 7: NaN Comparison
NaN is a unique value; it is never equal to itself.
console.log(NaN == NaN) // false
console.log(NaN === NaN) // false
console.log(typeof NaN) // "number"
// correct way to check
console.log(isNaN(NaN)) // true
console.log(Number.isNaN(NaN)) // trueFeel free to add more examples.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
JavaScript
Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
