Conditionals: if, else and switch
Course contents (16 lessons)
- Getting started
- What is JavaScript and where does it run?
- Variables with let and const
- Values and operators
- Data types: numbers, strings, booleans, null and undefined
- Operators: arithmetic, comparison and logical
- Strings and template literals
- Making decisions and repeating work
- Conditionals: if, else and switch
- Loops: for, while and for...of
- Functions
- Functions: declarations, parameters and return values
- Arrow functions and callbacks
- Arrays and objects
- Arrays: creating, reading and changing lists
- Array methods: map, filter, find and reduce
- Objects: properties, methods and copying
- Scope and the browser
- Scope and closures, gently
- The DOM: selecting and changing elements
- Events: reacting to clicks, input and forms
- Final project
- Project: build a to-do list in the browser
Programs need to choose
Up to now our code ran from top to bottom, one line after another. Real programs need to make choices. Show the login form or the dashboard. Charge shipping or not. A conditional runs a block of code only when a condition is true.
if, else if and else
function describeTemperature(celsius) {
if (celsius >= 35) {
return "very hot";
} else if (celsius >= 25) {
return "warm";
} else if (celsius >= 15) {
return "mild";
} else {
return "cold";
}
}
console.log(describeTemperature(40)); // very hot
console.log(describeTemperature(28)); // warm
console.log(describeTemperature(10)); // cold
JavaScript checks the conditions from top to bottom. The first one that is true wins, its block runs, and the rest are skipped. That is why the order matters. If we had put celsius >= 15 first, 40 degrees would be called "mild".
The final else is optional. It catches everything that did not match above.
Curly braces are technically optional for a one-line body, but I always write them. Code without braces is a common source of bugs when someone adds a second line later and assumes it belongs to the if.
Conditions can be any expression
The condition inside the brackets is turned into a boolean. As we saw in the types lesson, these values count as false: false, 0, "", null, undefined and NaN. Everything else counts as true.
const name = "";
if (name) {
console.log("Hello, " + name);
} else {
console.log("Please enter your name");
}
This is called a truthy or falsy check. It is short and common, but it fails when 0 is a valid value:
const items = 0;
if (items) {
console.log("You have items");
} else {
console.log("Basket is empty"); // correct here
}
const rating = 0;
if (rating) {
console.log("Rated");
} else {
console.log("Not rated"); // wrong, 0 is a real rating
}
When zero or an empty string is a legal value, compare explicitly: if (rating !== undefined).
Combining conditions
Use &&, || and ! to build bigger conditions.
const age = 22;
const hasId = true;
if (age >= 18 && hasId) {
console.log("Entry allowed");
}
const day = "Sunday";
if (day === "Saturday" || day === "Sunday") {
console.log("Weekend");
}
If a condition grows past two or three parts, put pieces into named variables:
const isAdult = age >= 18;
const canEnter = isAdult && hasId;
if (canEnter) { /* ... */ }
That reads like English and is far easier to debug.
Early return
Deep nesting makes code hard to follow. A trick I use all the time is to deal with the bad cases first and return early.
function shippingCost(total, country) {
if (total <= 0) return 0;
if (country !== "PK") return 2500;
if (total >= 5000) return 0;
return 300;
}
console.log(shippingCost(6000, "PK")); // 0
console.log(shippingCost(1200, "PK")); // 300
console.log(shippingCost(1200, "AE")); // 2500
Each line handles one rule and exits. There is no pyramid of nested braces.
switch
When you compare one value against many fixed options, switch can be tidier:
function dayType(day) {
switch (day) {
case "Saturday":
case "Sunday":
return "weekend";
case "Friday":
return "almost weekend";
default:
return "weekday";
}
}
console.log(dayType("Sunday")); // weekend
console.log(dayType("Monday")); // weekday
switch uses strict comparison (===). Two cases stacked with no code between them, like Saturday and Sunday, share one result. The default runs when nothing matches.
If you do not use return inside each case, you must end it with break. Without it, JavaScript "falls through" and runs the next case as well, which is almost never what you want:
switch (1) {
case 1:
console.log("one");
break;
case 2:
console.log("two");
break;
}
For a small number of branches, if and else if is fine. I use switch when I have four or more fixed values.
Common mistakes
- Writing = instead of ===.
if (score = 10)assigns and always passes. Your editor often warns about this. - Wrong order of checks. Put the most specific condition first.
- Truthy checks on zero. Be explicit when 0 or an empty string is valid.
- Forgetting break in switch. The next case runs too.
- Comparing strings of different case.
"yes" === "Yes"is false. Normalise withtoLowerCase()first.
Try it yourself
- Write a function
grade(score)that returns "A" for 80 and above, "B" for 70 to 79, "C" for 60 to 69 and "Fail" below that. - Write a check that prints "leap year" when a year is divisible by 4, except for years divisible by 100 unless they are also divisible by 400. Test with 1900, 2000 and 2024.
- Rewrite
dayTypewithifstatements and compare which version reads better to you. - Make a function that takes
"red","yellow"or"green"and returns what a driver should do.
function describeTemperature(celsius) {
if (celsius >= 35) {
return "very hot";
} else if (celsius >= 25) {
return "warm";
} else if (celsius >= 15) {
return "mild";
} else {
return "cold";
}
}
console.log(describeTemperature(40)); // very hot
console.log(describeTemperature(28)); // warm
console.log(describeTemperature(10)); // cold
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account