Lesson Objectives
By the end of this lesson, you will be able to:
- Use
if
,else if
andelse
to run code branches conditionally. - Write
for
,while
anddo…while
loops to repeat work. - Combine conditionals and loops to solve common problems (e.g., finding max values, filtering arrays).
- 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 wherefn(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>
-
Grab DOM elements in
index.js
:const input = document.getElementById('threshold') const button = document.getElementById('filterBtn') const output = document.getElementById('app')
-
Define your data:
const numbers = [1, 4, 9, 16, 25]
-
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(', ')}]`
-
-
Bonus: Let users pick ascending vs. descending before filtering, then sort accordingly.
Reflection
- When is a
while
loop more suitable than afor
loop? - What are the pros and cons of loop+conditional vs.
.filter()
/.sort()
? - What if the user enters invalid input or no input at all?