Series: JavaScript 101
- About JavaScript 101
- Hello World in Web Browser
- Hello World in Node.js
- Variable in JavaScript
- Data Types in JavaScript
- Array in JavaScript
- Object in JavaScript
- Spread Operator in JavaScript
- Loops in JavaScript
- Conditional Statements in JavaScript
- Functions in JavaScript
- Object-Oriented Programming in JavaScript
Conditional statements are an important concept in programming, and JavaScript is no exception. The if/else statements allow you to make decisions in your code based on whether a certain condition is met.
The basic syntax for an if/else statement in JavaScript is as follows:
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
To put it simply, if/else statements are like a fork in the road. Based on the condition specified, your code will either take the path of the if statement or the else statement.
For example, you might use an if statement to check if a user is of legal drinking age before serving them alcohol in a simulation program. If the user is over 21, they would be served the alcohol, and if they are under 21, they would not be served.
const isOverTwentyOne = true
if (isOverTwentyOne) {
console.log("Here's your alcohol!");
} else {
console.log("Sorry we could not serve you alcohol");
}
In the if statement, you specify the condition you want to check. If the condition evaluates to true, the code inside the if block will run. If the condition evaluates to false, the code inside the else block will run. It's important to note that the else block is optional, so you can choose to only use an if statement if you don't need to specify an alternate action.
if/else statements allow you to make decisions in your code based on conditions, giving you greater control over the flow of your programs. With this knowledge, you'll be well on your way to writing more complex and dynamic programs in JavaScript.