Welcome to conditional logic! Every interactive website needs to make decisions: Is the user logged in? Did they enter the correct password? Is this item in stock?
JavaScript uses if
statements to execute code only if a specific condition is true.
Engagement Message
Name one decision a website makes using information about you.
An if
statement follows this pattern:
if (condition) {
// code to run if condition is true
}
The condition, which must evaluate to true
or false
, goes in parentheses. The code to execute goes between the curly braces.
Engagement Message
What do you think happens if the condition is false?
Remember comparison operators? They're perfect for creating the conditions in if
statements.
if (age >= 18) {
// show content for adults
}
This code block only runs if the value stored in the age
variable is or greater.
