We can check if two values are not equal using the inequality operator. There is a soft inequality operator, != and a hard inequality operator, !==. These work in a similar way to the soft and hard equality operators:
16 != '16'; // type coercion makes these equal<< false
16 !== '16';<< true
As with equality, a ninja programmer should use the hard inequality operator as this will give more reliable results unaffected by type coercion.
To make it very easy. != is only testing the value while !== Test also the type. So 16 is an integer while ‘16’ is a string. Both have the same value but not the same type
Yeah it’s actually much worse, the loose equality operator does some hard to comprehend (and not even transitive) type coercions… see here for the gory details:
x = 5
x != 8 true. got it x 5 does not equal 5
x !== 5 false. this says x 5 is NOT equal to five, false. because 5 does equal 5
x !== "5" true. x is not equal to type
x !== 8 true. x does not equal 8
Correct. != checks the coerced values to attempt to evaluate the right side as the same as the left; !== checks type first, then value. (if the type check fails, theres no point in coercing and checking the value)
5 == “5” is true.
5 === “5” is false.
Inverting those equalities simply flips the truth:
5 != “5” is false.
5 !== “5” is true.
Should you use strict/hard/type-sensitive equalities? Usually, yes, its better practice to use them, especially when it comes to equating things to an empty or 0 value, so called “truthy” evaluations. A lot of languages, Javascript included, will coerce things like 0, "", [], false all to be equal in loose equalities - if, for (admittedly, more of a PHP one, but) example, you check a database, did you get 0 records, or a false indicating a problem with your query? only strict checking can tell.
There are very little use cases for using the loose equality check, and if you do want to compare possibly mixed types (such as the value of an input element with a number, say) it’s always better to explicitly convert the type first to clarify your intent.
In fact, I’d suggest to use a linter that will warn about loose equality checks; by just always using the strict one, you can be sure not to accidentally forget a = which would make your program behave differently, and which would be hard to spot otherwise.