Comparison and logical operators are used to test true or false.
Comparison Operators
Comparison operators are used in logical statements to determine whether variables or values are equal.
Given x=5, the following table explains the comparison operators:
运算符 | 描述 | 例子 |
---|---|---|
== | 等于 | x==8 为 false |
=== | 全等(值和类型) | x===5 为 true;x==="5" 为 false |
!= | 不等于 | x!=8 为 true |
> | 大于 | x>8 为 false |
< | 小于 | x<8 为 true |
>= | 大于或等于 | x>=8 为 false |
<= | 小于或等于 | x<=8 为 true |
if (age<18) document.write("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 following table explains the logical operators:
运算符 | 描述 | 例子 |
---|---|---|
&& | and | (x < 10 && y > 1) 为 true |
|| | or | (x==5 || y==5) 为 false |
! | not | !(x==y) 为 true |
Syntax
variablename=(condition)?value1:value2
Example
greeting=(visitor=="PRES")?"Dear President ":"Dear ";
If the variable visitor If the value is "PRES", assign the value "Dear President" to the variable greeting, otherwise assign the value "Dear".