Introduction
JavaScript is a popular programming language used for creating interactive web pages and applications. It provides a variety of control flow statements that allow developers to control the execution of code. In this blog, we will discuss the various control flow statements in JavaScript.
1. If-else statements:
The if-else statement is used to execute a block of code based on a certain condition. The code inside the if statement will be executed if the condition is true, otherwise, the code inside the else statement will be executed.
Syntax:
Example:
Explanation:
In this example, the if statement checks whether the age variable is greater than or equal to 18. If the condition is true, the code inside the curly braces {} after the if statement will be executed, which in this case is to log the message "You are old enough to vote." If the condition is false, the code inside the curly braces after the else keyword will be executed, which in this case is to log the message "You are not old enough to vote."
Here's another example that uses more complex conditions:
Explanation:
In this example, the if statement checks whether the current time is before 12pm. If the condition is true, the code inside the curly braces after the if statement will be executed, which in this case is to log the message "Good morning!" If the condition is false, the next condition will be checked, which is whether the current time is before 6pm. If that condition is true, the code inside the curly braces after the else if keyword will be executed, which in this case is to log the message "Good afternoon!" If both conditions are false, the code inside the curly braces after the else keyword will be executed, which in this case is to log the message "Good evening!"
I hope this helps you understand how to use if-else statements in JavaScript! Let me know if you have any other questions.If you liked this post follow and like for more contents.
Oldest comments (2)
I try to avoid such if-else or if-else-if constructions. In my opinion, the following is much clearer.
wow thanks for sharing.
your code is much easier to read.