2.9 Making Decisions with if and else Statements

15 min read
70

In the previous tutorial, “2.7 Working with Strings and Template Literals,” we explored the creation of strings using template literals. In this tutorial, “2.9 Making Decisions with if and else Statements,” let’s elevate our coding experience by incorporating decision-making into our code, making it more dynamic and realistic.

if and else Statements

Imagine we want to develop a program that assesses whether an individual is eligible to obtain a driver’s license. If eligible, the program will print a message to the console indicating so. Conversely, if not eligible, it will display the number of years remaining until the person can commence the process.

To kick things off, let’s focus on the individual’s age, set at 19 in this scenario. We already know how to verify if this age meets the minimum requirement of 18, the legal age for obtaining a driver’s license here in India. Let’s create a variable to store this age:

let age = 19;

if statement

Let’s create another variable to assess eligibility for a driving license based on age. And you remember to check if the age is at least 18, we need it to be greater or equal than 18, and so it will then include 18. So, when the age is exactly 18, the outcome of this comparison will be true. However, if the age is 17, 16, or anything below, the result will be false:

let isOldEnough = age >= 18;

Now that we have a Boolean value, we can use it to make decisions with an ‘if statement.’ The ‘if statement’ structure involves the keyword ‘if,’ followed by an open parenthesis, the condition to be evaluated inside the parentheses, and then a closing parenthesis. If the condition is true, the code block enclosed by curly braces ‘{}‘ will be executed.

In this context, the condition is a Boolean value, and we can use our ‘isOldEnough‘ variable for this purpose, given that it always holds a Boolean value:

if (isOldEnough) {
  console.log("Aaradhya can start the driving license process");
}

In this example, “Aaradhya can start the driving license process” will be displayed because the age is 19, surpassing 18. Consequently, when ‘isOldEnough‘ is true, the code block within the curly braces will execute. Note that while the current example involves only one line of code, the code block could potentially consist of multiple lines.

ALSO READ:  2.1 Introduction to JavaScript Values and Variables

So, let’s consider a different scenario—take age 15, where isOldEnough is now false. Consequently, the block of code within {console.log("Aaradhya can start driving license");} should not be executed:

age = 15;
isOldEnough = age >= 18;

if (isOldEnough) {
  console.log("Aaradhya can start driving license");
}

In this case, no output is generated, indicating that the condition has been properly implemented.

Now, if we change the age to 19:

age = 19;
isOldEnough = age >= 18;

if (isOldEnough) {
  console.log("Aaradhya can start driving license");
}

Once again, the output is “Aaradhya can start driving license.”

In practice, it is common to streamline the code by directly writing the condition, like this:

if (age >= 18) {
  console.log("Aaradhya can start driving license");
}

This approach is more commonly used.

else statement

Let’s reset the age to 15 and introduce a new element this time—adding an ‘else‘ block. After initializing the age variable to 15, we incorporate the ‘else‘ block immediately following the initial ‘if‘ block.

age = 15;

Now, if we delve into the purpose of this ‘else‘ block, it comes into play when the condition “age >= 18” is false. Given the current age of less than 18, this condition is indeed false, rendering the initial ‘if‘ block inactive. Consequently, the control flows to the ‘else‘ block.

Within the ‘else‘ block, we implement code to determine the remaining years until Aaradhya qualifies for a driving license, as we outlined earlier. The code snippet looks like this:

if (age >= 18) {
  console.log("Aaradhya can start driving license");
} else {
  const yearsLeftToDrive = 18 - age; // 3
  console.log(`Aaradhya is too young to get a driving license. Wait another ${yearsLeftToDrive} years.`);
}

Effectively, the ‘else‘ block’s code executes since the “age >= 18” condition evaluates to false. Consequently, the output reflects the situation: “Aaradhya is too young to get a driving license. Wait another 3 years.”

ALSO READ:  2.11 Type Conversion and Coercion in JavaScript

It’s essential to note that the inclusion of the ‘else‘ block is not mandatory. Omitting it would still yield a functional outcome. In such cases, JavaScript proceeds to the subsequent line following the ‘if statement’ in instances where the condition proves false.

if (age >= 18) {
  console.log("Aaradhya can start driving license");
} else {
  const yearsLeftToDrive = 18 - age; // 3
  console.log(`Aaradhya is too young to get a driving license. Wait another ${yearsLeftToDrive} years.`);
}

if/else statement

Now that you’ve familiarized yourself with the concept of an if/else statement and its functionality, it’s crucial to recognize its significance in programming. Decision-making through code is a fundamental aspect, and the if/else statement, formally referred to as a control structure, plays a pivotal role.

In essence, a control structure, exemplified by the if/else statement, provides a mechanism for exerting influence over the execution flow of our code. The if/else construct allows us to make decisions based on specified conditions, thereby determining which sections of our program should be executed.

if () {
} else {
}

This control structure deviates from the linear execution pattern seen in basic code sequences. Unlike the sequential execution of all code in languages like JavaScript, the if/else statement empowers us to selectively control the execution of distinct code blocks. This enhanced control proves instrumental in shaping the functionality of our code.

By utilizing if/else and other control structures, we gain a deeper level of control over our code’s execution, enabling us to dictate which code blocks are executed and which are bypassed. As we delve further into programming, we’ll explore additional control structures that contribute to refining our code’s behavior.

In summary, the if/else statement, as a control structure, elevates our ability to manage the execution flow of code, offering a more nuanced and controlled programming experience. This foundational understanding sets the stage for exploring other control structures in subsequent learning sessions.

Example

To ensure your comprehension of this concept, let’s illustrate it with another concise example. Rather than consistently using console.log(), we will create a variable conditionally.

Consider the creation of a ‘birthYear‘ variable. Next, let’s generate a ‘century‘ variable to encapsulate the century of the individual’s birth. In this instance, it was the 20th century. However, if, for example, the birth year was 2015, it would be the 21st century. To achieve this, we can employ an if/else statement:

let birthYear = 1991;
let century;

if (birthYear <= 2000) {
  century = 20;
} else {
  century = 21;
}

To make this function correctly, we must define the ‘century‘ variable outside the ‘if/else’ block. The reason for this will be explored later, but for now, understand that any variable declared within a code block, such as {let century = 20;}, will not be accessible outside that block.

ALSO READ:  2.10 Coding Challenge-2: Calculate Grade Average

Attempting to read ‘century‘ at this point will result in an error:

console.log(century); // Uncaught ReferenceError: century is not defined

This error occurs because ‘century‘ only exists within the ‘if and else statements.’ To rectify this, we need to declare ‘century‘ outside and leave it uninitialized. Then, inside the ‘{let century = 20;}‘ and ‘{let century = 21;}‘ blocks, we can conditionally reassign it:

let birthYear = 1998;
let century;

if (birthYear <= 2000) {
  century = 20;
} else {
  century = 21;
}

Now, observe how this functions:

console.log(century); // 20

Indeed, we obtain the 20th century as the result. For instance, if the birth year is 2012, it should now be the 21st century:

birthYear = 2012;

if (birthYear <= 2000) {
  century = 20;
} else {
  century = 21;
}

console.log(century); // 21

This yields the expected outcome.

In summary, understanding the if/else statement’s logic is crucial. The placement of the ‘century‘ variable outside the blocks is a technical necessity. Once this logic is clear, you can confidently tackle the next challenge, which is coming next tutorial.

Frequently Asked Questions (FAQs) on if and else Statements in JavaScript

Learning is an ever-evolving experience, and encountering questions and uncertainties is a natural part of the learning journey. To assist you in navigating this process, we have assembled a collection of Frequently Asked Questions (FAQs) focused on “Making Decisions with if/else Statements in JavaScript.” Whether you need clarification on precedence usage or have lingering doubts, you’ll probably find the answers in the following FAQs. Take the opportunity to delve into and refine your understanding of if/else statements.

Avatar for Amit

Amit (16)

Hello! I'm Amit Kumar, a passionate teacher specializing in web development and digital marketing. With several years of experience in the industry, I am dedicated to sharing my knowledge and expertise to empower aspiring learners like you.

Teaching Philosophy:

I believe in creating a dynamic and engaging learning environment where students can thrive. My teaching approach focuses on hands-on experience, practical applications, and real-world examples. I strive to make complex concepts understandable and enjoyable, ensuring that you not only grasp the fundamentals but also develop the skills necessary to excel in web development and digital marketing.

Web Development Expertise:

As a web development instructor, I am well-versed in HTML, CSS, JavaScript, and various frameworks such as React and Angular. I will guide you through the process of building responsive and user-friendly websites, exploring topics like front-end development, back-end integration, database management, and more. Together, we will delve into the latest trends and best practices in web development, equipping you with the tools to create stunning online experiences.

Digital Marketing Mastery:

In the rapidly evolving digital landscape, digital marketing is crucial for businesses to thrive. Through my digital marketing courses, I will help you navigate the intricacies of search engine optimization (SEO), social media marketing, content strategy, email marketing, and analytics. Gain insights into effective marketing techniques, harness the power of data-driven decision-making, and learn how to craft compelling campaigns that drive results.

Passion for Teaching:

Teaching is not just a profession for me; it's my passion. I find great joy in witnessing my students grow and succeed. I am committed to fostering a supportive learning community where questions are encouraged, ideas are shared, and challenges are overcome together. I am here to guide you every step of the way and provide the necessary resources for your personal and professional development.

Join me on this exciting journey of learning and discovery. Let's unlock your potential in web development and digital marketing together. Enroll in my courses today and embark on a transformative educational experience that will propel your career forward.
Start Learning Today!

5 1 vote
Article Rating
Subscribe
Notify of

guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Scroll to Top