Introduction To Programming | Operator | Function |
|---|---|
== |
Tests whether two expressions are equal |
!= |
Tests whether two expressions are not equal |
=== |
Tests whether two expressions are really equal |
!== |
Tests whether two expressions are really not equal |
These operators are used in "if" and "while" statements. We'll add those in the next unit but here's some samples showing what they look like.
Boolean expressions are just statements that are either true or false.
Does 5 equal 5?
(5 === 5) True!
Does "Fred" equal "Barney"?
("Fred" === "Barney") False!
If a variable named 'count' has a value of 3. What is result of this expression?
(count === 3) True!
How about this?
(100 === "100") ???
We can see the results of an equality test with a simple document.write();
==)The
==operator has a trick. It will convert types to match before it does the equality test.
(100 == "100") What will this be? It's true!
The "100" will first be converted to the number 100 and then compared to 100.
It does NOT convert the case of strings.
You can use variables in the test
!=)The
!=operator will convert types and then test to see if the values are not equal. This can be confusing, if the values are not equal then the test returnstrue.
The 25 will be converted to "25" and then tested for inequality with the "25". Because they are equal the test will return false.
This test will return true because 10 is not equal to 11.
Just convert ("Bob" != "Bill") into a question: "Is 'Bob' different from 'Bill'?" Yes, they are different.
===)The
===operator will not do any conversions, it will just do a strict comparison. If the types don't match then you getfalse. This is the equality operator that we'll use most of the time.
If they are the same type then it's just the same as ==
This will now return false.
!==)The
!==tests for inequality with no type conversion.
This works like != with no type conversion so we often get different results.
For numbers it's just the same as !=.
== (And why you shouldn't use it).JavaScript's auto-conversion can sometimes give us unexpected results. Here's an example. What do you think this should be?
('' == 0) true or false?
Is that what we want to happen? What happens with ===?