JS Tutorial
JS Version
JS Objects
JS Function
JS Classes
JS Async
JS HTML DOM
JS Browser BOM
JS Web API
JS AJAX
JS JSON
JS vs JQUERY
JS Graphics
JavaScript Comparison and Logical Operators
Comparison and Logical operators are used for testing for true or false.
How Can it Be Used?
Comparison operators can be used in conditional statements for comparing values and taking action depending on the result:
if (age < 18) text = “Too young to buy alcohol”;
Logical Operators
Logical operators determine the logic between variables or values.
Given that x = 6 and y = 3, the table below explains the logical operators.
Operator | Description | Example | Try it |
&& | and | (x < 10 && y > 1) is true | |
|| | or | (x == 5 || y == 5) is false | |
! | not | !(x == y) is true |
Conditional (Ternary) Operator
JavaScript consists of conditional operator that are used to assign a value to a variable based on some condition.
Syntax
variablename = (condition) ? value1:value2
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Comparison</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 Comparison
Input your age and click the button:
Comparing Different Types
Comparing data of different types may give unexpected results.
When a string is compared with a number, JavaScript converts the string to a number while doing the comparison. An empty string converts to 0.
Case | Value | |
2 < 12 | true | |
2 < “12” | true | |
2 < “John” | false | |
2 > “John” | false | |
2 == “John” | false | |
“2” < “12” | false | |
“2” > “12” | true | |
“2” == “12” | false |
When comparing two strings, “2” will be greater than “12”, because (alphabetically) 1 is less than 2.
Variables must be converted to the proper type before comparison:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Comparisons</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 voteable;
let age = Number(document.getElementById(“age”).value);
if (isNaN(age)) {
voteable = “Input is not a number”;
} else {
voteable = (age < 18) ? “Too young” : “Old enough”;
}
document.getElementById(“demo”).innerHTML = voteable + ” to vote”;
}
</script>
</body>
</html>
Output
JavaScript Comparisons
Input your age and click the button: