DEV Community

Cover image for If, else in javascript.
Ali Sina Yousofi
Ali Sina Yousofi

Posted on

If, else in javascript.

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:

Image description

Example:

Image description

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:

Image description

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.

Top comments (2)

Collapse
 
frankwisniewski profile image
Frank Wisniewski

I try to avoid such if-else or if-else-if constructions. In my opinion, the following is much clearer.

//replace if else
let age  = 17
let ageTest  = ""
if (age < 18) ageTest = "not "
console.log(`You are ${ageTest}eligible to vote`)

// replace if else if
let time = new Date().getHours()
let timeOfDay = "afternoon"
if (time > 18) timeOfDay = 'evening'
if (time < 12) timeOfDay = 'morning'
console.log(`Good ${timeOfDay}!`)  
Enter fullscreen mode Exit fullscreen mode
Collapse
 
alisinayousofi profile image
Ali Sina Yousofi

wow thanks for sharing.
your code is much easier to read.