Comparison and logical operators are used to test for true or false.
Comparison operators
Comparison operators are used in logical statements to determine whether a variable or value is equal.
Given x=5, the following table explains the comparison operators:
Operator Description Examples
= = equals x==8 to False
= = = Congruent (value and type) x===5 to true;x=== "5" is false
! = does not equal x!=8 to True
> Greater than X>8 to False
< less than X<8 is true
>= greater than or equal to x>=8 false
<= less than or equal to X<=8 is true
How to use
You can use comparison operators to compare values in a conditional statement and then take action based on the result:
if (age<18) document.write ("Too Young");
You'll 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:
Operator Description Examples
&& (x < && y > 1) True
|| or (x==5 | | y==5) is false
! Not! (x==y) is true
Conditional operators
JavaScript also includes conditional operators that assign values to variables based on certain conditions.
Grammar
Variablename= (condition)? value1:value2
Example
Greeting= (visitor== "PRES")? " Dear president ":" Dear ";
If the value in the variable visitor is "PRES", assign a value of "Dear president" to the variable greeting, otherwise assign a value of "Dear".
<! DOCTYPE html>
<body>
<meta http-equiv= "Content-type" content= "text/html charset=utf-8"/>
<script>
function Print ()
{
var age = 15;
if (age < 18)
document.write ("Too Young");
var visitor = "PRES";
var greeting= (visitor== "PRES")? " Dear president ":" Dear ";
document.write (greeting);
}
</script>
<td><input type= "text" name= "TxtRow1" id= "Txt1" size= "+"/></td>
<button onclick= "Print ()" > click here </button>
</body>
javascript--comparison