Operators and Conditions

Table of Contents

  1. Operators Do the Work
  2. Comparison and Equality
  3. Truthy and Falsy
  4. if, else if, else
  5. switch
  6. Logical Operators: &&, ||, !
  7. Safe Defaults: ?? and ?.
  8. The Ternary Operator
  9. Recipe: A Time-of-Day Greeting
  10. 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:

OperatorMeaningExampleResult
+Add7 + 29
-Subtract7 - 25
*Multiply7 * 214
/Divide7 / 23.5
%Remainder7 % 21
**Power7 ** 249

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:

OperatorNameBehavior
===Strict equalitytrue only if value and type match
==Loose equalityConverts 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:

OperatorNameMeaning
&&ANDTrue when both sides are true
||ORTrue when at least one side is true
!NOTFlips 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

  1. Even or odd. Write code with let number = 7; that prints "even" or "odd" using % and an if/else. Try several numbers.
  2. Strict vs. loose. Predict the result of 0 === false, 0 == false, "" == 0, and null === null. Run them and check.
  3. Grade a score. Given score, print A for 90 and above, B for 80 to 89, C for 70 to 79, and Try again for anything lower, using else if.
  4. Weekday names. Use new Date().getDay() (0 is Sunday) and a switch to print the name of today. Add a default for safety.
  5. Fix the default. Write const volume = 0; then compare volume || 50 with volume ?? 50. Explain in one sentence which one is correct for a volume setting.
  6. 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!