JavaScript Comparison and Logical Operators



JavaScript Comparison and Logical Operators

  • Comparison and Logical operators are used to test for true or false.

Comparison Operators

  • Comparison operators are used in logical statements to determine equality or difference between variables or values.
  • Given that x = 5, the table below explains the comparison operators.
Operator Name Example Return Value
== Equal to a==b True or false
a==3 True or false
a=="3" True or false
=== Equal value and types a===b True or false
a===="3" True or false
!= Not equal to a!=b True or false
!== Not equal to and types a!==b True or false
a!=="b" True or false
> Greater than a>b True or false
< Less than a<b True or false
>= Greater than or equal to a>=b True or false
<= Less than or equal to a<=b True or false

How Can it be Used

  • The Comparison operators can be used in conditional statements to compare values and take action depending on the result:
if (age < 18) text = "Too young to buy alcohol";

Logical Operators

  • Logical operators are used to determine the logic between variables or values.
Operator Description Example
&& AND (x < 10 && y > 1) is true
|| OR (x == 5 || y == 5) is false
! NOT !(x == y) is true

Syntax

let voteable = (age < 18) ? "Too young":"Old enough";
js-logical-operators

Sample Code

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The () ? : Ternary Operator</h2>

<p>Input your age and click the button:</p>

<input id="age" value="18" />

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
  let age = document.getElementById("age").value;
  let voteable = (age < 18) ? "Too young":"Old enough";
  document.getElementById("demo").innerHTML = voteable + " to vote.";
}
</script>

</body>
</html>

Output

javascript-logical-operators
javascript-comparison-and-logical-operators

Related Searches to JavaScript Comparison and Logical Operators