JavaScript – Operators – Arithmetic – Assignment
Comparison and Logical operators are used to determine equality or difference between variables or values. The final result is true or false.
Conditional Operators assign a value to a variable based on some condition.
The code:
<!DOCTYPE html> <html> <body> <p>Given that x=5 y=10, return the value of the comparison:</p> <button onclick="myFunction()">Return the value of x==y</button> <p id="demo"></p> <script> function myFunction() { var x=5; var y=10; var z=x==y; // the variable store - false - document.getElementById("demo").innerHTML=z; // render the result - false - } </script> </body> </html>
Complete list:
<!DOCTYPE html> <html> <body> <script> var x=5; // number var y=10; // number var z="5"; // string // Comparison Operators var a=x==y; // equal value -> result false var a=x==z; // equal value -> result true var a=x===z; // equal value and type -> result false var a=x!=y; // not equal value -> result false var a=x!==y; // not equal value and type -> result false var a=x!==z; // not equal value and type -> result true var a=x>y; // greater than -> result false var a=x<y; // less than -> result true var a=x>=y; // greater than or equal to -> result false var a=x<=y; // less than or equal to -> result true // Logical Operators if (x < 10 && y > 1)... you want to do ... -> and (true se entrambe le condizioni vere) if (x < 10 || y > 1)... you want to do ... -> or (true se una delle condizioni è vera) if !(x==y) ... you want to do ... -> not (true se entrambe le condizioni sono false) </script> </body> </html>
Conditional Operators:
<!DOCTYPE html> <html> <body> <p>Click the button to check the age.</p> Age:<input id="age" value="18" /> <p>Old enough to vote?</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var age,voteable; age=document.getElementById("age").value; voteable=(age<18)?"Too young":"Old enough"; document.getElementById("demo").innerHTML=voteable; } </script> </body> </html>
Notice:
voteable=(age<18)?"Too young":"Old enough";
Syntax:
variablename=(condition)?value1:value2
If the condition is true the variable stores value1
If the condition is false the variable stores value2