JavaScript Conditions (if/else) Tutorial 🎯

beginner
23 min

JavaScript Conditions (if/else) Tutorial 🎯

Welcome to our deep dive into JavaScript Conditions! In this comprehensive guide, we'll explore the if, else, and else if statements, which are fundamental control structures in JavaScript that help make your code more dynamic and interactive. Let's get started!

What are Conditions in JavaScript? 📝

In simple terms, conditions allow your JavaScript code to make decisions based on certain rules or criteria. They let your scripts evaluate expressions and perform different actions based on the result. This is a key aspect of programming that allows for more complex and interactive applications.

The if Statement 💡

The if statement is the most basic condition in JavaScript. It evaluates an expression and executes code if the result is true.

javascript
// Example: Check if a number is greater than 10 let number = 15; if (number > 10) { console.log("The number is greater than 10."); }

In this example, the code checks if the number is greater than 10. If it is, it logs "The number is greater than 10." to the console.

The else Statement 💡

The else statement is used in conjunction with the if statement to execute code when the if condition evaluates to false.

javascript
// Example: Check if a number is greater than 10 and if not, say it's less let number = 5; if (number > 10) { console.log("The number is greater than 10."); } else { console.log("The number is less than or equal to 10."); }

Here, the code checks if the number is greater than 10. If it is, it logs "The number is greater than 10.". If not, it logs "The number is less than or equal to 10.".

The else if Statement 💡

The else if statement is used when you want to check multiple conditions. It checks the first condition, if it's false, it moves to the next one, and so on.

javascript
// Example: Check number and assign a category let number = 15; if (number > 20) { console.log("The number is in the high range."); } else if (number > 10) { console.log("The number is in the medium range."); } else { console.log("The number is in the low range."); }

In this example, the code checks if the number is greater than 20. If it is, it logs "The number is in the high range.". If not, it checks if the number is greater than 10. If it is, it logs "The number is in the medium range.". If neither condition is true, it logs "The number is in the low range.".

Quiz 📝

Quick Quiz
Question 1 of 1

What will the following code print?