Conditional Logic: If / Else
The if/else
statement runs a block of code if a condition is true, and another block if it's false. It's like making a decision.
let yourNumber = 15;
if (yourNumber > 10) {
// This code runs if the number is greater than 10
} else {
// This code runs otherwise
}
Try it yourself:
Result:
Repeating Actions: The 'For' Loop
A for
loop is perfect for running a piece of code a specific number of times. It has three parts: an initializer, a condition, and an incrementer.
for (let i = 1; i <= 5; i++) {
// This code will run 5 times
}
Try it yourself:
Result:
Conditional Looping: The 'While' Loop
A while
loop keeps running as long as its condition is true. It's useful when you don't know exactly how many times you need to loop.
let count = 0;
while (count < 3) {
// This code runs as long as count is less than 3
count++;
}
Try it yourself:
Result:
Combining Conditions: Logical Operators
Logical operators are used to combine multiple conditions. The main ones are &&
(AND), ||
(OR), and !
(NOT).
let isHungry = true;
let hasFood = true;
// AND (&&): both must be true
if (isHungry && hasFood) { /* Time to eat! */ }
// OR (||): at least one must be true
if (isTired || isBored) { /* Time to rest. */ }
// NOT (!): inverts the value (true becomes false)
if (!isRaining) { /* Go outside! */ }