Comparison and logical operators are used to test true or false .
Comparison operators are used in logical statements to determine whether variables or values are equal.
We are given x = 5, and the comparison operators are explained in the following table:
|==||equal||x == 8||false|
|x == 5||true|
|x == "5"||true|
|===||Equal values and types||x === 5||true|
|x === "5"||false|
|! =||Not equal||x! = 8||true|
|! ==||Values or types are not equal||x! == 5||false|
|x! == "5"||true|
|x! == 8||true|
|>||greater than||x > 8||false|
|<||less than||x < 8||true|
|>=||greater than or equal to||x >= 8||false|
|<=||less than or equal to||x <= 8||true|
How to use
Comparison operators can be used to compare values in conditional statements and take action based on the result:
if (age < 18) text = "too young";
You will learn more about conditional statements in the following chapters of this tutorial.
Logical operators are used to determine the logic between variables or values.
We have given x = 6 and y = 3, the following table explains the logical operators:
|&&||versus||(x < 10 && y > 1) fortrue|
|||||or||(x == 5 || y == 5) forfalse|
|!||Non||!(x == y) fortrue|
Conditional (ternary) operator
variablename = ( condition )? value1 : value2
var voteable = (age < 18) ? "Too young": "Mature enough";
If the value of the variable age is less than 18, the value of the variable voteable will be "too young", otherwise the value of the variable voteable will be "mature enough".