Functions: packaging code you'll reuse
A function is a labeled block of code you can run whenever you need it, with different inputs each time. name here is a parameter โ a placeholder for whatever value you pass in when you call the function. return sends a value back out.
Arrow functions: the modern shorthand
You'll see both styles constantly in real code. Arrow functions are the more common style in modern JavaScript, especially for short functions.
if / else: making decisions
The code inside { } after if only runs if the condition is true. The else block is the fallback for everything else.
else if: checking multiple conditions
JavaScript checks each condition top to bottom and stops at the first one that's true โ so order matters. This example correctly prints "B".
Comparison and logical operators
| Operator | Meaning |
|---|---|
> < >= <= | Greater than, less than, and their "or equal to" versions |
=== !== | Equal to / not equal to (always use these, not ==) |
&& | AND โ both sides must be true |
|| | OR โ at least one side must be true |
Loops: repeating actions
A for loop has three parts: where to start (let i = 0), when to stop (i < 5), and what happens after each round (i++, which adds 1). This is the most common loop for "do this a specific number of times."
i++) creates an infinite loop that freezes your page. If your browser tab suddenly locks up while testing a loop, this is almost always why.
Try it yourself
checkAge(age) that returns "child" if under 13, "teen" if 13-17, and "adult" for 18 and up, using if/else if/else. Test it by calling it with three different ages and logging each result.
Level up: a counting loop
for loop that logs every even number from 0 to 20. Hint: you can check if a number is even with number % 2 === 0 (the % gives you the remainder after division).
1. What does a function's return statement do?
2. In a for loop, what does forgetting to update the loop variable cause?
3. What does && require to be true?
if/else makes decisions, and loops repeat actions without copy-pasting code. Together, these are what turn a script into a program that actually reacts to different situations.