Control Flow
The if
and else
keywords are some of the most useful in Javascript, as they allow our program to have conditional logic. They let our program do different things based on the value of an expression, which is often checking the value of a variable. To create an if statement, you start with the keyword if
, followed by brackets ()
that surround the condition that you’re checking is true, followed by curly brackets {}
with the code to be executed inside of them. Optionally, you can have an else
following the curly brackets for the if statement, and the code in the else block will execute if the condition is false.
const age = 18
if (age >= 18) {
console.log("You are an adult")
} else {
console.log("You are a minor")
}
When writing if statements, we need to be able to write conditional statements that evaluate to true or false, as seen in the example above. The common operators are shown in the table below (with the true
or false
coming from the assumption that let x = 10
)
Operator | Description | Example |
---|---|---|
=== | Equals | x === 10 (true) |
!== | Not equals | x !== 10 (false) |
> | Greater than | x > 10 (false) |
< | Less than | x < 10 (false) |
>= | Greater than or equal to | x >= 10 (true) |
<= | Less than or equal to | x <= 10 (true) |