1 example

Implicit type coercion

Automatic type conversions causing unexpected behaviors.

[ FAQ1 ]

What is implicit type coercion?

Implicit type coercion occurs when a language like JavaScript automatically converts values from one data type to another to perform an operation, without explicit instruction from the developer. While intended as a convenience, implicit coercion often results in subtle bugs or unexpected behavior—for example, the loose equality operator (==) in JavaScript converts types implicitly, leading to confusing comparisons. Developers might unintentionally rely on coercion, introducing logical errors, unpredictable outcomes, and complicating debugging and maintenance.
[ FAQ2 ]

How to fix implicit type coercion bugs

To fix implicit type coercion bugs, explicitly perform type conversions or comparisons, clearly specifying intended behavior in your code. Replace loose equality operators (==) with strict equality operators (===) in JavaScript to prevent unintended type conversions. Utilize strict mode or tools like TypeScript to enforce explicit typing and avoid coercion-related errors proactively. Regularly review and test your code logic, focusing on comparisons and arithmetic operations, ensuring clarity, correctness, and predictable behavior.
diff block
function evalToString(ast /* : Object */) /* : string */ {
switch (ast.type) {
case 'StringLiteral':
+ return ast.value + ''; // Unnecessary string conversion
case 'Literal': // ESLint
- return ast.value;
+ return ast.value || ''; // Silent failure for null/undefined values
Greptile
greptile
style: Using || for null/undefined creates implicit type coercion. Consider explicit null check instead.