Conditionals
Conditionals are used to perform different actions based on different conditions. They allow your code to make decisions and execute certain blocks of code depending on whether a condition is true or false (an incredible power!). This is fundamental for creating dynamic and interactive programs.
1. The (classic) IF Statement
The if
statement is the most basic form of conditional statement. It executes a block of code if a specified condition is true. It’s easy:
Syntax:
Example:
In this example, the message "You are eligible to vote." will be printed to the console if the value of age
is 18 or greater.
2. The (more complete) IF … ELSE Statement
The if...else
statement allows you to execute one block of code if a condition is true and another block of code if the condition is false.
Syntax:
Example:
In this example, the message "You are not eligible to vote." will be printed to the console because the value of age
is less than 18.
3. The (perfect shape) IF … ELSE IF … ELSE Statement
The if...else if...else
statement is used to specify a new condition to test if the first condition is false. This allows for multiple conditions to be tested in sequence.
Syntax:
Example:
In this example, the message "Grade: B" will be printed to the console because the value of score
is between 80 and 89.
4. The (alternative) SWITCH Statement
The switch
statement is used to perform different actions based on different conditions. It is an alternative to using multiple if...else if
statements and can make your code easier to read when you have many conditions to check.
Syntax:
Example:
In this example, the message "Wednesday" will be printed to the console because the value of day
is 3.
Use Case:
Suppose you're building a simple application to determine the type of message to display based on the time of day. You might use conditionals to check the current hour and display an appropriate message.
Example:
In this example:
We use the
getHours
method to get the current hour from theDate
object.We use
if...else if...else
statements to set thegreeting
variable based on the current hour.We use
console.log
to print the appropriate greeting to the console.
This use case demonstrates how conditionals can be used to create dynamic and context-sensitive behavior in your JavaScript programs. Understanding these fundamental control structures is essential for building interactive and responsive applications.
Help us improve the content 🤩
You can leave comments here.
Last updated