Michael Ouroumis logoichael Ouroumis
← Back to course

“Conditions & Control Flow”

Learn how to use `if`/`else` statements and loops to direct your code’s execution.

Lesson Objectives

By the end of this lesson, you will be able to:

  1. Use if, else if and else to run code branches conditionally.
  2. Write for, while and do…while loops to repeat work.
  3. Combine conditionals and loops to solve common problems (e.g., finding max values, filtering arrays).
  4. Use array methods like .filter() and .sort() for declarative data transformations.

1. if / else

JavaScript’s if statement lets you choose which code path to take:

const age = 18 if (age >= 18) { console.log('You can vote!') } else { console.log('Not old enough to vote.') }

else if

Chain additional tests with else if:

const score = 75 if (score >= 90) { console.log('A') } else if (score >= 80) { console.log('B') } else if (score >= 70) { console.log('C') } else { console.log('Needs improvement') }

2. Loops

Loops let you repeat code:

  • for – known number of iterations:

    for (let i = 0; i < 5; i++) { console.log(i) }
  • while – repeat while a condition holds:

    let count = 3 while (count > 0) { console.log(count) count-- }
  • do…while – run at least once:

    let n = 0 do { console.log('This runs once.') } while (n > 0)

3. Combining Loops & Conditionals

Example: Find the largest value in an array.

const nums = [3, 7, 2, 9, 5] let max = nums[0] for (const n of nums) { if (n > max) { max = n } } console.log(`The largest number is ${max}`)

4. Array Methods: filter & sort

Instead of an explicit loop + if, you can use:

  • .filter(fn) returns a new array of items where fn(item) is true.
  • .sort(fn) rearranges an array based on your compare function.
const numbers = [1, 4, 9, 16, 25] // filter out values < threshold const threshold = 10 const filtered = numbers.filter((n) => n >= threshold) console.log(filtered) // [16, 25] // sort ascending or descending const asc = [...filtered].sort((a, b) => a - b) const desc = [...filtered].sort((a, b) => b - a)

Task: Build a Number Filter

Your HTML scaffold already includes:

<div id="app"></div> <input id="threshold" type="number" placeholder="Enter threshold" /> <button id="filterBtn">Filter Numbers</button>
  1. Grab DOM elements in index.js:

    const input = document.getElementById('threshold') const button = document.getElementById('filterBtn') const output = document.getElementById('app')
  2. Define your data:

    const numbers = [1, 4, 9, 16, 25]
  3. Add a click listener that:

    • Reads Number(input.value), validates it.

    • Uses either a loop + if or .filter() to get values ≥ threshold.

    • Applies .sort((a,b)=>…) based on a user-chosen order (e.g. add a <select> for “asc”/“desc”).

    • Renders into output, e.g.:

      output.textContent = `Values ≥ ${threshold}: [${filtered.join(', ')}]`
  4. Bonus: Let users pick ascending vs. descending before filtering, then sort accordingly.


Reflection

  1. When is a while loop more suitable than a for loop?
  2. What are the pros and cons of loop+conditional vs. .filter()/.sort()?
  3. What if the user enters invalid input or no input at all?

Try It Yourself

// 1. grab DOM elements
const input = document.getElementById('threshold')
const button = document.getElementById('filterBtn')
const output = document.getElementById('app')

// 2. our data
const numbers = [1, 4, 9, 16, 25]

// 3. filter & render when clicked
button.addEventListener('click', () => {
  const threshold = Number(input.value)
  if (Number.isNaN(threshold)) {
    output.textContent = 'Please enter a valid number.'
    return
  }

  const filtered = numbers.filter((n) => n >= threshold)
  output.textContent = `Values ≥ ${threshold}: [${filtered.join(', ')}]`
})