On this page

Operators, conditionals, and loops

12 min read TextCh. 1 — Fundamentals

Comparison operators

JavaScript has two types of equality:

  • Strict (===, !==) — Compares value and type. Always preferred
  • Loose (==, !=) — Performs type coercion before comparing. Avoid it
0 === false   // false (different type)
0 == false    // true  (coercion: false -> 0)
'' === false  // false
'' == false   // true  (coercion: '' -> 0, false -> 0)

Logical operators

Operator Name Description
&& AND True if both are true
|| OR True if at least one is true
! NOT Inverts the value
?? Nullish coalescing Returns the right side if the left is null or undefined

Nullish coalescing vs OR

The key difference is that ?? only considers null and undefined as "empty", while || also considers 0, '', and false:

const quantity = 0;
console.log(quantity || 10);  // 10 (0 is falsy)
console.log(quantity ?? 10);  // 0  (0 is not null or undefined)

Conditionals

if / else if / else

The most common structure for control flow. It evaluates conditions sequentially and executes the first block whose condition is true.

Ternary operator

The ternary operator is useful for conditional assignments in a single line:

const message = points > 100 ? 'You won' : 'Keep trying';

Switch

Use switch when you have multiple possible values for the same variable. Do not forget break to avoid unintended fall-through.

Loops

JavaScript offers several ways to iterate:

Loop Recommended use
for When you need the index
for...of To iterate over arrays and other iterables
for...in To iterate over object keys
while When you don't know how many iterations there will be
do...while Like while, but executes at least once

break and continue

  • break — Exits the loop completely
  • continue — Skips to the next iteration

Truthy and falsy values

JavaScript converts values to boolean in conditional contexts. The falsy values are: false, 0, -0, 0n, "", null, undefined, and NaN. Everything else is truthy.

if ([]) console.log('truthy');  // executes: empty array is truthy
if ({}) console.log('truthy');  // executes: empty object is truthy

Practice

  1. Write a classifier function: Create a function that receives an age and returns 'minor', 'teenager', or 'adult' using if/else if/else. Test it with the values 10, 15, and 25.
  2. Use nullish coalescing and OR: Declare a variable quantity with value 0 and log the difference between quantity || 10 and quantity ?? 10. Explain why the results differ.
  3. Iterate an array with for...of: Create an array colors with 5 colors and iterate it with for...of, printing each color in uppercase with toUpperCase(). Use continue to skip the third element.

In the next lesson we will learn about modern functions in JavaScript.

Avoid == (loose equality)
Always use === (strict equality). Loose equality == performs type coercion and produces unexpected results such as 0 == '' being true.
Prefer for...of
Use for...of to iterate over arrays. It is more readable than the classic for loop and works with any iterable (strings, Maps, Sets, etc.).
javascript
// Comparison operators
console.log(5 === '5');   // false (strict)
console.log(5 == '5');    // true  (coercion)
console.log(5 !== '5');   // true

// Logical operators
const age = 20;
const hasPermission = true;
const canEnter = age >= 18 && hasPermission;
const isStudent = age < 25 || age > 60;

// Nullish coalescing
const name = null;
const greeting = name ?? 'Guest';
console.log(greeting); // "Guest"

// Conditionals
if (age >= 18) {
  console.log('Adult');
} else if (age >= 13) {
  console.log('Teenager');
} else {
  console.log('Minor');
}

// Ternary
const type = age >= 18 ? 'adult' : 'minor';

// Switch
const day = 'monday';
switch (day) {
  case 'monday':
  case 'tuesday':
    console.log('Start of the week');
    break;
  case 'friday':
    console.log('End of the work week');
    break;
  default:
    console.log('Another day');
}
javascript
const fruits = ['apple', 'banana', 'cherry'];

// Classic for
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

// for...of (values) - recommended for arrays
for (const fruit of fruits) {
  console.log(fruit);
}

// for...in (keys) - useful for objects
const config = { theme: 'dark', language: 'en' };
for (const key in config) {
  console.log(`${key}: ${config[key]}`);
}

// while
let attempts = 3;
while (attempts > 0) {
  console.log(`Remaining attempts: ${attempts}`);
  attempts--;
}

// break and continue
for (const fruit of fruits) {
  if (fruit === 'banana') continue;
  console.log(fruit); // skips banana
}