2.12 Truthy and Falsy Values in JavaScript

34 min read
274

We’ve covered type conversion and type coercion for numbers and strings. However, we haven’t discussed Booleans yet. This omission is intentional because we first need to understand the concept of truthy and falsy values. That’s what we’re going to delve into now, so let’s dive right in.

Understanding Truthy and Falsy Values

Falsy values are not explicitly false, but will evaluate to false when converted to a Boolean.

In JavaScript, there are five key falsy values, and I’ll list them for you:

  1. 0
  2. ''
  3. undefined
  4. null
  5. NaN
Note:
Naturally, the value “false” itself is already inherently false, so there’s no need to include it in the list of falsy values.

To reiterate, the five falsy values will consistently convert to false when subjected to a Boolean conversion. Although these values don’t start off as false, they transform into false when treated as Booleans.

That encapsulates the definition of falsy values. Everything else falls into the category of truthy values. For instance, any non-zero number or any non-empty string will convert to true when undergoing a Boolean conversion.

Example-1:

Now, let’s observe this in action. Similar to our previous exploration with numbers and strings, we can employ the Boolean function—Boolean followed by the value. Let’s take 0 as an example, a well-known falsy value:

console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean(undefined)); // false
console.log(Boolean(null)); // false
console.log(Boolean(NaN)); // false
console.log(Boolean("Amit")); // true
console.log(Boolean({})); // true

As expected, the conversion of 0, an empty string, undefined, null, and NaN to a boolean results in false. Conversely, the string "Amit" and an empty object {} evaluate to true. This aligns with our understanding that any non-empty string and any non-empty object are truthy values. Conversely, attempting to convert an empty string, as anticipated, yields false, given its status as a falsy value, as indicated in the list of the ‘five falsy values.’

ALSO READ:  2.3 JavaScript Data Types: The Building Blocks of Programming

In essence, that’s the essence of truthy and falsy values and how we convert them to Booleans.

However, in real-world scenarios, I’ve never explicitly used the Boolean function. The conversion to Boolean is always implicit, a form of typed coercion executed automatically by JavaScript behind the scenes.

Example-2:

So, when does JavaScript engage in type coercion to Booleans? This occurs in two scenarios:

  1. When using logical operators
  2. In a logical context, such as the condition of an if/else statement

While we’ll delve into logical operators in a subsequent tutorial, let’s revisit the if/else statement now to understand how type coercion operates in its condition.

Consider a scenario where we have an availableFunds variable, initially set to zero, indicating a lack of funds. Now, utilizing our newfound knowledge, we can examine whether the person currently possesses any money or not:

let availableFunds = 0;

if (availableFunds) {
  console.log("Avoid using all of your available funds.");
} else {
  console.log("Consider finding employment to increase your funds!");
}

Surprisingly, we observe the "Consider finding employment to increase your funds!" message, triggering the else block. But why? availableFunds is presently a number, specifically zero. Yet, within the logical context of an if/else statement condition (enclosed in parentheses), JavaScript attempts to coerce any value into a Boolean.

Irrespective of what we place in the condition, if it’s not already a Boolean, JavaScript endeavors to convert it. This conversion aligns with the truthy and falsy value rules discussed earlier. In this case, even though availableFunds is zero, zero is a falsy value. Consequently, within the logical condition (availableFunds), the numerical zero is transformed into false. This parallels the manual conversion we performed in the previous example, where console.log(Boolean(0)); yielded false when zero was explicitly converted to a Boolean.

Consequently, the else block is executed, and the console displays "Consider finding employment to increase your funds!"

Example-3:

Now, let’s change the value of availableFunds to something else—any number will suffice. For example, let’s set it to 99. In this case, 99 is a truthy value, meaning the condition will evaluate to true. Consequently, the if block will be executed. Interested in seeing the result?

availableFunds = 99;

if (availableFunds) {
  console.log("You have enough savings for a vacation.");
} else {
  console.log("Save more before planning your vacation.");
}

Indeed, the output now reads, "You have enough savings for a vacation." Excellent! I hope this clarification resonates.

ALSO READ:  1.2 Introduction to JavaScript

To further reinforce your understanding, let’s explore another scenario. An additional application of truthy and falsy values is to verify whether a variable is defined or not. While this may initially appear unconventional, you’ll discover in later tutorials that checking for the existence of something is a meaningful and practical use case.

Example-4:

Let’s introduce a variable named personHeight, and proceed with the following:

let personHeight;

if (personHeight) {
  console.log("Hooray! The person's height has been defined!");
} else {
  console.log("The value of the person's height is undefined.");
}

As anticipated, the output is "The value of the person's height is undefined." This outcome is expected because, at this point, personHeight is not assigned any value. As per our list of ‘5 falsy values,’ we are aware that undefined is one such falsy value. Consequently, analogous to the earlier example with the availableFunds variable, the personHeight variable, in this logical context, is automatically coerced into a Boolean. Given that personHeight is undefined and undefined is a falsy value, personHeight is evaluated as false. Consequently, the else block is executed.

Example-5:

Now, if we assign any value to it, the outcome will change, regardless of what that value is.

// Assign a value to the height variable.
personHeight = 108;

if (personHeight) {
  console.log("Hooray! The person's height has been defined!");
} else {
  console.log("The value of the person's height is undefined.");
}

Now, it will display, "Hooray! The person's height has been defined!" because the personHeight variable has a defined value.

Example-6:

However, there’s a potential issue that can arise. Consider a scenario where the height is zero, a perfectly valid number. Let’s see what happens when we execute the code:

// Another scenario where the height is zero.
personHeight = 0;

if (personHeight) {
  console.log("Hooray! The person's height has been defined!");
} else {
  console.log("The value of the person's height is undefined.");
}

Now, it outputs, "The value of the person's height is undefined." Why does this occur?

ALSO READ:  2.9 Making Decisions with if and else Statements

As you might have gathered by now, the reason is that zero is also a falsy value, triggering the else block.

However, in this case, this outcome is not desirable; it’s a bug in our application. The else statement did not account for the scenario where the height is zero. We only considered whether the height is defined or not, without considering the possibility of the height being zero. As a result, the output incorrectly indicates that the height is undefined, which is not accurate. This serves as an example to highlight potential issues with this approach.

Nevertheless, we can rectify this using logical operators, which will be explored in a later tutorial. Stay tuned for that! In the upcoming tutorial, we’ll delve into equality operators, so be sure to stay tuned for more insights.

FAQs – Understanding Truthy and Falsy Values, Type Coercion, and Explicit Type Conversion in JavaScript

Embarking on the journey of mastering JavaScript involves navigating through various concepts, each contributing to a richer understanding of the language. To assist you on this learning voyage, we present a curated set of Frequently Asked Questions (FAQs) delving into the intricacies of “Truthy and Falsy Values,” “Type Coercion,” and “Explicit Type Conversion in JavaScript.”

Whether you’re grappling with the subtleties of truthy and falsy values or aiming to demystify the processes of type coercion and explicit type conversion, our FAQs are designed to cater to a diverse range of inquiries. Take advantage of this valuable resource to enhance your grasp of these fundamental concepts in the realm of JavaScript. Happy learning!

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