Operators and Conditions
Table of Contents
- Operators Do the Work
- Comparison and Equality
- Truthy and Falsy
- if, else if, else
- switch
- Logical Operators: &&, ||, !
- Safe Defaults: ?? and ?.
- The Ternary Operator
- Recipe: A Time-of-Day Greeting
- Try It Yourself
1. Operators Do the Work
An operator is a symbol that combines values into a new value. You
already used + and =. Here are the arithmetic operators:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Add | 7 + 2 | 9 |
- | Subtract | 7 - 2 | 5 |
* | Multiply | 7 * 2 | 14 |
/ | Divide | 7 / 2 | 3.5 |
% | Remainder | 7 % 2 | 1 |
** | Power | 7 ** 2 | 49 |
The remainder operator % is more useful than it looks. n % 2 === 0
tells you whether n is even.
Operators can be combined with assignment as a shortcut:
let score = 10;
score += 5; // same as score = score + 5 -> 15
score -= 3; // 12
score++; // add one -> 13
console.log(score);
2. Comparison and Equality
Comparison operators produce a boolean (true or false):
console.log(5 > 3); // true
console.log(5 <= 3); // false
console.log(5 !== 3); // true: "not equal"
For equality there are two versions, and the difference is important:
| Operator | Name | Behavior |
|---|---|---|
=== | Strict equality | true only if value and type match |
== | Loose equality | Converts types first, then compares |
console.log(5 === "5"); // false: number vs. string
console.log(5 == "5"); // true: "5" was converted to 5
console.log(0 == ""); // true (surprising)
console.log(null == undefined); // true
console.log(null === undefined); // false
Loose equality follows complicated conversion rules that few people
remember. Always use === and !==. This whole series does, and most
teams' style rules require it.
3. Truthy and Falsy
An if statement needs a condition. When the condition is not a boolean,
JavaScript converts it. Every value is either truthy (acts like true)
or falsy (acts like false).
There are only a few falsy values. Memorize this list:
false, 0, -0, 0n, "", null, undefined, NaN
Everything else is truthy, including "0", " ", [] (an empty array),
and {} (an empty object). Check with Boolean():
console.log(Boolean("Dara")); // true
console.log(Boolean("")); // false
console.log(Boolean(0)); // false
console.log(Boolean([])); // true <-- empty array is truthy
Truthiness gives you a short way to ask "is there a value?" For example,
if (name) is true when name is a non-empty string. Be careful when 0
is a valid value: if (count) is false when count is 0.
4. if, else if, else
An if statement runs a block of code only when a condition is truthy:
const age = 17;
if (age >= 18) {
console.log("Adult");
} else if (age >= 13) {
console.log("Teenager");
} else {
console.log("Child");
}
This prints Teenager. JavaScript checks the conditions from top to
bottom and runs the first block that matches, then skips the rest.
The else at the end catches everything else, and it is optional.
Always use the curly braces { }, even for a single line. It prevents
mistakes when you add a second line later.
5. switch
When you compare one value against many exact options, switch is
cleaner than a long else if chain:
const day = "Sat";
switch (day) {
case "Sat":
case "Sun":
console.log("Weekend");
break;
case "Fri":
console.log("Almost the weekend");
break;
default:
console.log("Weekday");
}
This prints Weekend. Each case compares with ===. The break
ends the switch; without it, JavaScript continues running into the next
case ("fall through"). Here, "Sat" has no break on purpose, so it
shares code with "Sun". The default runs when nothing matches.
Use switch for a list of exact values. Use if for ranges such as
hour < 12.
6. Logical Operators: &&, ||, !
Logical operators combine conditions:
| Operator | Name | Meaning |
|---|---|---|
&& | AND | True when both sides are true |
|| | OR | True when at least one side is true |
! | NOT | Flips true to false and false to true |
const hour = 14;
const isWorkHours = hour >= 9 && hour < 17;
console.log(isWorkHours); // true
console.log(!isWorkHours); // false
These operators have a useful feature: they return one of their two
values, not just true or false, and they stop early ("short
circuit"). || returns the first truthy value, and && returns the first
falsy one:
const nickname = "";
console.log(nickname || "Friend"); // "Friend": "" is falsy, so use the backup
console.log(true && "Shown"); // "Shown"
|| is often used for default values, but it has a problem: it treats
0 and "" as "missing", even when they are real answers. The next
section solves this.
7. Safe Defaults: ?? and ?.
Nullish coalescing (??) gives a default only when the left side is
null or undefined. It leaves 0, "", and false alone:
const likes = 0;
console.log(likes || 10); // 10 (wrong: 0 is a real count)
console.log(likes ?? 10); // 0 (correct)
Optional chaining (?.) safely reads a property of something that
might not exist. Without it, reading a property of undefined stops the
program with an error:
const dara = { name: "Dara", address: undefined };
// console.log(dara.address.city); // TypeError: Cannot read properties of undefined
console.log(dara.address?.city); // undefined: no crash
console.log(dara.address?.city ?? "City not given"); // "City not given"
The pair ?. and ?? is common: read something that might be missing,
then supply a fallback. (Objects are explained fully in chapter 6.)
8. The Ternary Operator
The ternary operator is a short if/else that produces a value. It
has three parts: condition ? valueIfTrue : valueIfFalse.
const projectCount = 1;
const label = projectCount === 1 ? "project" : "projects";
console.log(`${projectCount} ${label}`); // "1 project"
Use it for simple choices between two values. If you nest ternaries or the
line becomes long, use a normal if instead. Readability matters more
than saving lines.
9. Recipe: A Time-of-Day Greeting
Dara's page should greet the visitor depending on the time. The method
new Date().getHours() returns the current hour from 0 to 23. We put
the decision in a small piece of code:
const hour = new Date().getHours();
let greeting;
if (hour < 12) {
greeting = "Good morning";
} else if (hour < 18) {
greeting = "Good afternoon";
} else {
greeting = "Good evening";
}
const visitorName = null;
const displayName = visitorName ?? "friend";
console.log(`${greeting}, ${displayName}! Welcome to Dara's page.`);
At 9:00 this prints Good morning, friend! Welcome to Dara's page.
Because the hour is checked from smallest to largest, the order of
conditions does the work: if hour is not below 12, we already know it
is 12 or more, so the next test only needs hour < 18.
Add the same code to js/main.js. In the browser it will print to the
Console for now. In chapter 8 you will show it on the page itself.
10. Try It Yourself
- Even or odd. Write code with
let number = 7;that prints"even"or"odd"using%and anif/else. Try several numbers. - Strict vs. loose. Predict the result of
0 === false,0 == false,"" == 0, andnull === null. Run them and check. - Grade a score. Given
score, printAfor 90 and above,Bfor 80 to 89,Cfor 70 to 79, andTry againfor anything lower, usingelse if. - Weekday names. Use
new Date().getDay()(0 is Sunday) and aswitchto print the name of today. Add adefaultfor safety. - Fix the default. Write
const volume = 0;then comparevolume || 50withvolume ?? 50. Explain in one sentence which one is correct for a volume setting. - Shorten with a ternary. Rewrite your even-or-odd code as a single line with the ternary operator. Which version is easier to read?
Next, we'll learn how to repeat work with loops, so you can process a whole list of projects instead of one value at a time. Continue with Loops and Iteration.
Buy Me a Coffee
Found this tutorial helpful? Consider buying me a coffee to support more free content!