JavaScript Zero to Advanced #3: Conditionals & Loops

So far our programs have run from top to bottom, one line after another. Real programs need to make decisions ("is this user an admin?") and repeat work ("send an email to every customer"). In this part you will learn both: conditionals and loops.
if, else if and else
An if statement runs a block of code only when a condition is true. Add else if for more cases and else for everything else:
const score = 78
if (score >= 90) {
console.log("Grade: A")
} else if (score >= 75) {
console.log("Grade: B")
} else if (score >= 60) {
console.log("Grade: C")
} else {
console.log("Grade: D")
}
Output:
Grade: B
Conditions are checked from top to bottom, and only the first matching block runs. Because 78 is not >= 90 but is >= 75, we get a B and the rest is skipped.
Combine conditions with && and ||:
const age = 20
const hasTicket = true
if (age >= 18 && hasTicket) {
console.log("Welcome to the concert!")
}
const day = "Sunday"
if (day === "Saturday" || day === "Sunday") {
console.log("It's the weekend")
}
Output:
Welcome to the concert! It's the weekend
Truthy and falsy values
A condition does not have to be a boolean. JavaScript converts any value to true or false when it is used in a condition. Only these values are falsy:
- false, 0, -0, 0n
- "" (empty string)
- null, undefined, NaN
Everything else is truthy, including "0", "false", [] and {}.
const values = [0, "", "hello", "0", null, [], {}, undefined, 42]
for (const value of values) {
console.log(JSON.stringify(value), "->", Boolean(value))
}
Output:
0 -> false
"" -> false
"hello" -> true
"0" -> true
null -> false
[] -> true
{} -> true
undefined -> false
42 -> true
This enables short checks like if (username) { ... }, which is true for any non-empty string.
The ternary operator and switch
For a simple either/or value, the ternary operator condition ? a : b is shorter than if/else:
const stock = 0 const label = stock > 0 ? "In stock" : "Sold out" console.log(label) const isMember = true const price = 100000 const finalPrice = isMember ? price * 0.9 : price console.log(finalPrice)
Output:
Sold out 90000
When you compare one value against many fixed options, switch can be easier to read:
function getDayType(day) {
switch (day) {
case "Saturday":
case "Sunday":
return "Weekend"
case "Friday":
return "Almost weekend"
default:
return "Weekday"
}
}
console.log(getDayType("Sunday"))
console.log(getDayType("Friday"))
console.log(getDayType("Tuesday"))
Output:
Weekend Almost weekend Weekday
switch uses strict equality (===). Inside a function we can return directly; outside one, each case must end with break, otherwise execution "falls through" into the next case.
for and while loops
The classic for loop has three parts: start, condition and update.
for (let i = 1; i <= 5; i++) {
console.log(`Step ${i}`)
}
Output:
Step 1 Step 2 Step 3 Step 4 Step 5
A while loop repeats as long as its condition is true. It is useful when you do not know in advance how many times to loop:
let balance = 100000
let months = 0
while (balance < 150000) {
balance = balance * 1.1
months++
}
console.log(`Months needed: ${months}`)
console.log(`Final balance: ${Math.round(balance)}`)
Output:
Months needed: 5 Final balance: 161051
There is also do...while, which always runs at least once because it checks the condition at the end.
for...of and for...in
To go through the items of an array (or the characters of a string), use for...of. To go through the keys of an object, use for...in:
const fruits = ["mango", "banana", "durian"]
for (const fruit of fruits) {
console.log(fruit.toUpperCase())
}
const user = { name: "Siti", city: "Surabaya", role: "admin" }
for (const key in user) {
console.log(`${key}: ${user[key]}`)
}
Output:
MANGO BANANA DURIAN name: Siti city: Surabaya role: admin
Rule of thumb: for...of for arrays and strings (values), for...in for plain objects (keys). Avoid for...in on arrays.
break and continue
break stops the loop completely. continue skips to the next iteration:
const numbers = [3, 8, -1, 12, 7, 20]
for (const n of numbers) {
if (n < 0) {
console.log("Negative found, skipping")
continue
}
if (n > 15) {
console.log("Too big, stopping")
break
}
console.log("Processing", n)
}
Output:
Processing 3 Processing 8 Negative found, skipping Processing 12 Processing 7 Too big, stopping
A classic: FizzBuzz
Here everything comes together: a loop, the modulo operator and an if/else if chain.
for (let i = 1; i <= 15; i++) {
if (i % 15 === 0) console.log("FizzBuzz")
else if (i % 3 === 0) console.log("Fizz")
else if (i % 5 === 0) console.log("Buzz")
else console.log(i)
}
Output:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
Common mistakes
- Using = inside a condition. if (role = "admin") assigns instead of comparing and is always truthy. Use ===.
- Infinite loops. Forgetting i++ or a condition that never becomes false will freeze the browser tab. Always check that the loop can end.
- Off-by-one errors. i <= array.length goes one step too far; the last index is array.length - 1.
- Forgetting break in switch. Without it, the next case runs too.
- Assuming [] is falsy. An empty array is truthy. Check array.length === 0 instead.
Exercise
Write a loop that goes from 1 to 30 and, for each number, prints whether it is even or odd using the ternary operator. Then extend it: stop the loop with break as soon as you reach the first number divisible by both 4 and 7. Which number is it, and how many lines were printed?
Summary
- if / else if / else runs the first block whose condition is true.
- Only false, 0, "", null, undefined and NaN (plus -0 and 0n) are falsy.
- Use the ternary operator for simple either/or values and switch for many fixed options.
- for and while repeat code; for...of loops over values, for...in over object keys.
- break exits a loop, continue skips the current iteration.
In Part 4 we will package logic into reusable functions and learn how scope and closures work.
Related articles
Next.js Zero to Advanced #1: Introduction & Project Setup
Meet Next.js, how it differs from React, and the App Router. We install Node.js, create the DigiStore project with create-next-app, tour its folders and run our first page.
PostgreSQL Zero to Advanced #1: Introduction & Setup
Start the series by understanding what a relational database is, installing PostgreSQL locally, and getting comfortable with psql commands like \l, \c and \dt.
PHP Zero to Advanced #1: Introduction & Setup
Start your PHP journey: what PHP is, how to install PHP 8.2+, run the built-in development server, and write your very first script with echo.