4.1 Comparison and Logical Operators
A comparison operator is an operator that compares two or more values or variables and returns either a true or false result.
The most common comparison operator in Javascript is the === operator. If we want to compare whether two variables are the same, we use the === operator (triple =). For instance, if you write x === y, you are asking the program to check if the value and data type of x and y are equal. If they are equal, the condition is met and the comparison evaluates to true. Else, the comparison evaluates to false.
To appreciate this, let's create a new file in Brackets and save it as chap4.js. Change the <script> tag in template.html to link to chap4.js. Add the following code to chap4.js.
console.log(2===2); console.log(2===3);
You'll get
true
false
as the output in the console window.
Besides the === operator, we also have the == operator (double =). The double = operator is not as strict as the triple = operator; it only requires the value of the two variables to be equal (whereas the triple = operator requires both the value and the data type to be the same).
For instance, if we have
var x = 2, y = 2, z = "2";
The statements
x == y;
x === y;
x == z;
all evaluate to true, while the statement
x === z;
evaluates to false as x is a number but z is a string.
You are advised to use the triple = operator whenever you want to perform an equality comparison. The double = operator may produce unexpected results which can lead to errors that are difficult to identify.
Besides the double and triple = operator, other comparison operators include != (not equal), !== (not equal in value or in type), < (smaller than), > (greater than), <= (smaller than or equal to) and >= (greater than or equal to). The list below shows how these operators can be used and gives examples of statements that evaluate to true.
Not equal:
5 != 2
Not equal in value or in type:
5 !== 2
5 !== "5"
Greater than:
5>2
Smaller than:
2<5
Greater than or equal to:
5>=2
5>=5
Smaller than or equal to:
2 <= 5
2 <= 2
As before, you are advised to use the !== operator when testing if one value is different from another. This is because !== is stricter than !=.
5 !== "5" gives us true while 5 != "5" gives us false.
Besides the comparison operators above, we also have two logical operators, && (and) and || (or) that are useful if we want to combine multiple comparisons.
The && operator returns true if all comparisons are true. Else it returns false. For instance, the statement 5===5 && 2>1 returns true as both comparisons are true.
The || operator returns true if at least one comparison is true. Else it returns false. The statement 5 > 2 || 7 > 10 || 3 === 2 returns true as the first comparison 5>2 is true.