JavaScript Conditions
Conditions let your program make decisions: run some code only when something is true.
The if Statement
Example
let marks = 72;
if (marks >= 50) {
console.log("Pass");
}Pass
The condition goes inside brackets. If it is true, the code block runs. If it is false, the block is skipped.
if...else
else runs when the condition is false:
Example
let hour = 21;
if (hour < 18) {
console.log("Shop is open");
} else {
console.log("Shop is closed");
}Shop is closed
else if
Use else if to test several conditions in order. The first true one wins, and the rest are skipped.
Example
<!DOCTYPE html>
<html>
<body>
<p>Enter marks: <input id="marks" type="number" value="83"></p>
<button onclick="grade()">Get grade</button>
<p id="demo"></p>
<script>
function grade() {
const m = Number(document.getElementById("marks").value);
let result;
if (m >= 90) {
result = "A+";
} else if (m >= 80) {
result = "A";
} else if (m >= 70) {
result = "B";
} else if (m >= 50) {
result = "C";
} else {
result = "Fail";
}
document.getElementById("demo").innerHTML = "Grade: " + result;
}
</script>
</body>
</html>Try it Yourself »Grade: A
Combining Conditions
Use && (and) and || (or) to test more than one thing:
Example
let age = 20;
let hasCnic = true;
if (age >= 18 && hasCnic) {
console.log("You can open a bank account");
}The Ternary Operator
For a simple either/or choice, the ternary operator condition ? valueIfTrue : valueIfFalse is a short form of if...else:
Example
let total = 2500;
let delivery = total >= 2000 ? 0 : 200;
console.log("Delivery charge: Rs " + delivery);Delivery charge: Rs 0
The switch Statement
switch compares one value against many fixed cases. break stops it from running into the next case.
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
let day;
switch (new Date().getDay()) {
case 0: day = "Sunday"; break;
case 1: day = "Monday"; break;
case 2: day = "Tuesday"; break;
case 3: day = "Wednesday"; break;
case 4: day = "Thursday"; break;
case 5: day = "Friday"; break;
case 6: day = "Saturday"; break;
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script>
</body>
</html>Try it Yourself »default can be added to handle any value that matches no case. switch uses strict comparison, like ===.
Truthy and Falsy
A condition does not need to be a boolean. JavaScript treats these values as falsy (like false):
| Falsy value | Meaning |
|---|---|
false | false |
0 | zero |
"" | empty string |
null | nothing |
undefined | no value |
NaN | not a number |
Everything else is truthy, including "0", "false" and empty arrays [].
Example
let username = "";
if (username) {
console.log("Hello " + username);
} else {
console.log("Please enter your name");
}Please enter your name
Order matters in else if chains. Put the strictest condition first. If you test m >= 50 before m >= 90, every good student would get a C.
Exercise
Exercise
What does this print? let x = 0; console.log(x ? "yes" : "no");
