After this lesson, you will learn how to use the if and else statements in JavaScript to make decisions in your code. These fundamental concepts allow you to dictate the flow of your program, which is critical for effective programming.
The if and else statements are vital for controlling the flow of your program. They let you execute different actions based on certain conditions. For example, consider a situation where you need to check if it is raining. If it is, you would take an umbrella; if it isn’t, you would leave without one. Here, you are making a decision based on the weather, which showcases how the if and else statements operate.
File: weather_check.js
let isRaining = true;
if (isRaining) {
console.log('Take an umbrella.');
} else {
console.log('No umbrella needed.');
}
Take an umbrella.
In this code:
let isRaining = true; declares a variable named isRaining and assigns it the value true.if statement checks if isRaining is true.console.log statement. However, if it’s false, it will execute the code inside else.Next, create a program that checks if a person is old enough to vote. Use an if statement along with an age variable. Print “You can vote!” if they are 18 or older; otherwise, print “You cannot vote yet.” This exercise will help reinforce your understanding of the if and else statements in JavaScript.
let age = 16;
if (age >= 18) {
console.log('You can vote!');
} else {
console.log('You cannot vote yet.');
}
Here are two common mistakes beginners often make:
== or === when making comparisons, not =.if or else, you must use curly braces.if and else statements are essential for making decisions in JavaScript.For additional resources, check out the What Is JavaScript? Examples from Everyday Websites lesson to broaden your understanding of JavaScript concepts.