JavaScript comparison and logical operators

JavaScript Comparison and Logical Operators


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:

QQ图片20161025111207.png

How to use

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

if (speed<180Km/h) document.write("Too fast");

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:


QQ图片20161025111806.png

Conditional operations

JavaScript also includes conditional operators that assign values ​​to variables based on certain conditions.

Syntax

variablename=(condition)?value1:value2

Example

greeting=(visitor=="PRES")?" Dear President ":"Dear ";

If the value in the variable visitor is "PRES", assign the value "Dear President" to the variable greeting, otherwise assign the value "Dear".



Continuing Learning
||
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <p>点击按钮检测年龄。</p> 年龄:<input id="age" value="18" /> <p>是否成年?</p> <button onclick="myFunction()">点击按钮</button> <p id="demo"></p> <script> function myFunction() { var age,voteable; age=document.getElementById("age").value; voteable=(age<18)?"未成年":"已成年"; document.getElementById("demo").innerHTML=voteable; } </script> </body> </html>
submitReset Code