Skip to content
Chapter 02 of 07 · 2 lessons · ~17 min

Logic and Loops

Teach your code to make decisions with if/else and to repeat work with loops, the two building blocks of every program.

YOUR PROGRESS0%
/ Lessons in this chapter
04
JavaScript If Else Statements How to make your code choose between options with if, else if, else, the ternary operator and switch. Coming soon
05
JavaScript Loops: for, while and forEach How to repeat code with for, for...of, while and forEach, and how to build page content from a list. Coming soon

Chapter practice task

Task: Show a time-based greeting and a list of your services

  1. Get the current hour with new Date().getHours().
  2. Show “Good morning”, “Good afternoon” or “Good evening” with if/else.
  3. Store your services in an array.
  4. Loop over the array and add each service to a list on the page.
  5. Highlight one service if it’s marked as “popular”.

By the end of this chapter

  • You can write if/else and switch statements with comparison and logical operators
  • You can repeat code with for, for…of, while and forEach
  • You can combine conditions and loops to build dynamic content

Quick answers for this chapter

What’s the difference between = and ===?

= assigns a value; === compares two values.

Which loop should I use?

for...of or forEach for arrays, a classic for when you need a counter.

Can a loop run forever?

Yes, if its condition never becomes false. That freezes the page, so always make sure the loop can end.