A Friendly Introduction to JavaScript Conditionals

A conditional is a statement that allows you to control the flow of your program based on certain conditions. In JavaScript, the most commonly used conditional statement is the if-else statement.

The basic structure of an if-else statement looks like this:

if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}

For example, let’s say you want to write a program that greets a user differently depending on the time of day. You can use an if-else statement to check the current time and display the appropriate greeting:

let currentTime = new Date().getHours(); //this method will fetch current hour

if (currentTime < 12) {
console.log("Good morning!");
} else if (currentTime < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}

In this example, the variable currentTime is set to the current hour using the Date object. The if statement checks if the current hour is less than 12. If it is, the code inside the if block is executed and the message “Good morning!” is displayed in the console.

If the current hour is not less than 12, the else if statement checks if the current hour is less than 18. If it is, the code inside the else if block is executed and the message “Good afternoon!” is displayed in the console.

If the current hour is not less than 18, the code inside the else block is executed and the message “Good evening!” is displayed in the console.

In addition to if-else statements, JavaScript also has a ternary operator, which is a shorthand way of writing a simple if-else statement. The syntax for a ternary operator looks like this:

condition ? true : false;

For example, the following ternary operator is equivalent to the if-else statement above:

let greeting = currentTime < 12 ? "Good morning!" : currentTime < 18 ? "Good afternoon!" : "Good evening!";

We covered the basics of conditionals in JavaScript and the most common type of conditional statement: the if-else statement. We also discussed the ternary operator, which is a shorthand way of writing a simple if-else statement.

Keep in mind, this is just a starting point and there are many more things you can do with conditionals in JavaScript. With practice and experience, you will be able to use them to create more complex and powerful programs. Happy coding!

Hello, I’m Anuj. I make and teach software.

My website is free of advertisements, affiliate links, tracking or analytics, sponsored posts, and paywalls.
Follow me on LinkedIn, X (twitter) to get timely updates when I post new articles.
My students are the reason this website exists. ❤️

Feedback Display Feedback Display

Leave a Reply

Your email address will not be published. Required fields are marked *