Conditional Statements: If and Else
Conditional statements in JavaScript allow you to perform different actions based on whether a certain condition is true or false. The most common type of conditional statement is the if
statement.
Here's a simple example:
In this code, we have a variable num
with a value of 10
. We use an if
statement to check if num
is greater than 5
. If it is, we use console.log()
to output the message "The number is greater than 5"
.
If the condition inside the parentheses is true
, the code inside the curly braces will be executed. If the condition is false
, the code inside the curly braces will be skipped.
Else Statements
You can also use an else
statement to execute a different piece of code if the condition is false
. Here's an example:
In this code, we have a variable num
with a value of 2
. We use an if
statement to check if num
is greater than 5
. Since num
is not greater than 5
, the code inside the if
block is skipped and the code inside the else
block is executed instead. This outputs the message "The number is less than or equal to 5"
.
Else If Statements
You can also use else if
statements to check for multiple conditions. Here's an example:
In this code, we have a variable num
with a value of 0
. We use an if
statement to check if num
is greater than 0
. Since num
is not greater than 0
, the code inside the if
block is skipped.
We then use an else if
statement to check if num
is less than 0
. Since num
is not less than 0
either, the code inside the else if
block is also skipped.
Finally, we use an else
statement to execute the code inside the last block, which outputs the message "The number is zero"
.
Challenge Time!
Let's imagine we have an elevator in our building. We want to write a program that will tell us if we can go up or down in the elevator or if we are already on the floor we want to go to.
You'll receive a variable currentFloor
which is the floor you are currently on. You'll also receive a variable destinationFloor
which is the floor you want to go to.
Write a program that will output one of the following messages:
"Go up"
ifcurrentFloor
is less thandestinationFloor
"Go down"
ifcurrentFloor
is greater thandestinationFloor
"Done"
ifcurrentFloor
is equal todestinationFloor