Conditions and loops
So far your code runs from top to bottom, one line after another, the same way every time. Real programs need to make decisions ("if the form is empty, show a warning") and repeat things ("do this for every item in the list"). That's what conditions and loops are for.
Comparing values
Before making decisions, you need a way to ask questions. Comparison operators compare two values and give you a boolean, true or false:
5 > 3 // true, greater than 5 < 3 // false, less than 5 >= 5 // true, greater than or equal 4 <= 3 // false, less than or equal 5 === 5 // true, equal 5 !== 3 // true, not equal
Notice the three equals signs in ===. One equals sign puts a value in a variable. Three equals signs compare two values.
You might see == with two equals signs in older code. It tries to be clever by converting types, so '5' == 5 is true, which causes sneaky bugs. Always use === and !==.
Which operator checks whether two values are equal?
Select one answer
if and else
An if statement runs some code only when a condition is true:
const temperature = 25;
if (temperature > 20) {
console.log('Time for ice cream!');
}The condition goes in parentheses and the code to run goes in curly braces. If the condition is false, the code in the braces is skipped.
Add else to handle the other case, and else if to check more conditions in order:
if (temperature > 25) {
console.log('Hot! Stay in the shade.');
} else if (temperature > 15) {
console.log('Nice weather.');
} else {
console.log('Bring a jacket.');
}JavaScript checks each condition from top to bottom and runs the first one that's true. Only one block ever runs.
Combining conditions
Sometimes you need to check two things at once:
&&means and: both sides must be true||means or: at least one side must be true!means not: it flips true to false and false to true
const age = 20;
const hasTicket = true;
if (age >= 18 && hasTicket) {
console.log('Welcome to the concert!');
}
const isWeekend = false;
if (!isWeekend) {
console.log('Time to study.');
}When is a && b true?
Select one answer
Truthy and falsy
Here's a handy shortcut. You can put any value in a condition, not just booleans. Some values count as false, and they're called falsy: 0, an empty string '', null, undefined and false itself. Everything else counts as truthy.
That's useful for checks like this:
const name = '';
if (!name) {
console.log('Please enter your name.');
}An empty string is falsy, so !name is true and the message shows up.
Loops: doing things over and over
Say you want to print the numbers 1 to 5. You could write five console.log lines, but what about 1 to 1000? That's where loops come in.
The classic for loop looks like this:
for (let i = 1; i <= 5; i++) {
console.log(i);
}It has three parts inside the parentheses, separated by semicolons:
let i = 1runs once at the start and creates a counteri <= 5is checked before each round. The loop continues while it's truei++runs after each round and adds 1 to the counter
So the loop prints 1, 2, 3, 4 and 5, then stops when i reaches 6.
for...of: looping through a list
Most of the time, you'll loop through a list of things. For that, there's a simpler loop called for...of:
const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
console.log(`I like ${fruit}`);
}Read it as "for each fruit in fruits". The loop runs once per item, and fruit holds the current item each time. You'll learn more about lists, called arrays, in a couple of lessons.
Watch out for endless loops
If a loop's condition never becomes false, it runs forever and freezes the browser tab. For example, forgetting the i++ in a for loop means i never changes. If your page suddenly stops responding, close the tab, check your loop and try again. It happens to everyone.
How many times does for (let i = 0; i < 3; i++) run?
Select one answer
Write some decisions and loops in script.js:
- Create a
const hour = new Date().getHours();which gives the current hour from 0 to 23 - Use
if,else ifandelseto log "Good morning", "Good afternoon" or "Good evening" depending on the hour - Write a
forloop that logs the numbers 1 to 10 - Create a list of three things you like and use
for...ofto log a sentence about each one
Bonus: change the greeting so it only logs if a name variable isn't empty, using what you learned about truthy and falsy.