== might not always be your best choice, and when it's appropriate to use
!= is known as the "not equal" or "inequality" operator. It checks whether two values are not equal and returns
true if they are indeed not equal. Here's a simple example:
!==. This operator not only checks if the values are not equal but also if they are of different types:
oranges have the same value numerically, they are of different types (string vs. number), hence not strictly equal.
You may wonder, why not to use
== operator is the "equal" operator that checks if two values are equal after performing type coercion if necessary. This can lead to unexpected results:
'3' (a string) is considered equal to
!= Mean in Code?
Since '3' is not equal to 4, the output is
When to use
== if you need type coercion and are certain it won't lead to unintended consequences. However, for a safer and more predictable comparison,
===, the strict equality operator, is generally recommended. It ensures both value and type are the same:
The first comparison returns
true because both operands are of the same type and value. The second comparison returns
false because, although their values are similar, their types are not.
In conclusion, understanding and using the correct comparison operators like
Join our community of forward-thinkers and innovators. Subscribe to get the latest updates on courses, exclusive insights, and tips from industry experts directly to your inbox.