![]() |
VOOZH | about |
JavaScript is a loosely typed or dynamic language, which means it automatically converts types when necessary, making it easier for developers to work with different data types in expressions, comparisons, and operations. However, this flexibility can sometimes lead to unexpected results if you're not careful.
In JavaScript, Type Coercion happens when JavaScript automatically changes one type of value into another. Sometimes, this automatic conversion can cause unexpected results if you’re not aware of how it works.
Output:
"510"In this example
In JavaScript, type coercion mainly occurs in the three ways:
It occurs when the string is combined with the non-string using (+). JavaScript converts numbers and booleans into strings before concatenation.
Output:
"52"
"5true"In the number coercion, JavaScript converts the string into a number before operating.
3 10 5
The string is coerced into a number before performing the arithmetic operation.
JavaScript treats the true value as '1' and the false value as '0'.
true false true
Non-empty strings are coerced to true, while 0 is coerced to false.
Comparison Operator(= =), allows coercion due to which the unexpected conversions occur. To avoid this, we should use the strict equality(= = =) operator.
true true true
Null and undefined behave unexpectedly.
true false 1
NaN is not equal to itself, so checking with isNaN() is the best way to detect it.
false true
In this example, NaN is not equal to itself, so the isNaN() function is the preferred way to check for NaN.
When we use strict equality, instead of the comparison operator, it prevents unnecessary types of coercion.
false
=== ensures no implicit type conversion occurs and both values must be of the same type.
Explicit conversion converts the value manually due to which there are fewer chances of errors in the code.
123
This ensures that you're working with the correct type, reducing the chance of errors during operations.
Always check for null, undefined, or empty strings explicitly.
if (value !== null && value !== undefined) {
console.log("Value exists");
}This ensures that only non-null and defined values are considered valid.
42 3.14
This will parse the number part of a string, ensuring a valid numeric conversion.
Use isNaN() to check if a value is NaN instead of comparing it directly.
if (isNaN(value)) {
console.log("Invalid number");
}This ensures you're correctly detecting NaN and handling it appropriately.