Comparison and Logical Operators are two of the main features of most if not all programming languages. They coupled with conditional statements form one of the basic building blocks of phone apps, programs, or functional interactions of websites. They are based off of the same logical and comparison operators that you find in math with only a little difference. I have listed the logical and comparison operators below and will go through some of examples of how they are used in programming with JavaScript.
//Comparison Operators
//Equal to and strict equal to
==
===
//Not equal to and strict not equal to
!=
!==
//Greater than and greater than or equal to
>
>=
//Less than and less than or equal to
<
<=
//Logical Operators
//And
&&
//Or
||
//Not
!
As you can see above, there are two different operators for equal to and not equal to. The equal to and not equal to operators allow you to compare the values of two variables regardless of the type and will return true or false depending on the matching values. The strict equal to operator requires that the variables and variable values match in order to return true. The strict not equal to returns true if the values or types do not match. You can see both in the below examples along with examples for the greater than and less than operators and a sample conditional statement.
let x = 3
let y = 4
x == 3 //true
x === “3” //false
x!=5 //true
x!== “5” //true
X!== 3 //false
y > 5 //false
y >= 3 //true
y < 5 //true
y <= 2 //false
if (x === 3){
/**comparison in if conditional
is true, so perform some code here**/
}
Logical operators in basic form are used to evaluate a compound conditional statement. They will return a Boolean value of true or false depending on the evaluation. JavaScript allows for the returning of different types and short-circuit evaluations, but that is for another post. Below are examples of the two logical operators.
let x = 15
let y = 23
x > 12 && y < 25 // True
x < 2 && y >12 // False
x > 12 || y > 25 // True
x < 2 || y < 12 // False
if (x < 45 && 32 > y){
/**compound comparison in if conditional
is true, so perform some code here**/
}
Top comments (1)
Don't forget about operator precedence. There are times when we have to add parentheses to group together compound conditionals.