Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript Comparison and Logical Operators

JavaScript Comparison and Logical Operators


Comparison and logical operators are used for testing true or false。


Comparison operators

Comparison operators are used in logical statements to determine whether variables or values are equal.

x=5, the table below explains the comparison operators:

operator Description Comparison Return Value Example
== Equal x==8 false Example »
x==5 true Example »
=== Strictly equal (both value and type are equal) x==="5" false Example »
x===5 true Example »
!=  Not equal x!=8 true Example »
!==  Strict not equal operator (either value or type is unequal, or both are unequal) x!=="5" true Example »
x!==5 false Example »
>  Greater than x>8 false Example »
<  Less than x<8 true Example »
>=  Greater than or equal to x>=8 false Example »
<=  Less than or equal to x<=8 true Example »


How to Use

You can use comparison operators in conditional statements to compare values and then take action based on the result:

if (age<18) x="Too young";

You will learn more about conditional statements in the next section of this tutorial.


Logical operators

Logical operators are used to determine the logic between variables or values.

Given x=6 and y=3, the table below explains the logical operators:

operator Description Example
&& and (x < 10 && y > 1) is true
|| or (x==5 || y==5) is false
! not !(x==y) is true


Conditional operator

JavaScript also includes a conditional operator that assigns values to variables based on certain conditions.

Syntax

variablename=(condition)?value1:value2 

Example

Example

If the value in the variable age is less than 18, assign "Too young" to the variable voteable, otherwise assign "Old enough".

voteable=(age<18)?"Too young":"Old enough";

Try it »