JavaScript Foundations: Truthy Vs Falsy

In JavaScript, values are broadly categorized into truthy and falsy values. Understanding this concept is essential for creating practical and concise true or false results. This article will delve into what makes a value truthy or falsy, provide examples, and demonstrate best practices when dealing with them.

Falsy Values

A falsy value is one that evaluates to false when used in a boolean context, such as in an if statement. JavaScript has only a handful of falsy values:

false – The boolean value false itself.

0 – The number zero (including -0).

""– An empty string (both single and double quotes).

null – The absence of any value.

undefined – A variable that has been declared but not assigned a value.

NaN – Not-a-Number, resulting from invalid mathematical operations.

Example:

if (!0) {
    console.log("0 is falsy"); 
}
if (!"") {
    console.log("An empty string is falsy"); 
}

Truthy Values

A truthy value is any value that is not falsy. This includes:

Non-empty strings: 'Hello','false','0'

Numbers other than0: 1, -1, 3.14

Arrays: []

Objects: {}

Functions:function() {}

true

Example:

if ("hello") {
    console.log("Non-empty strings are truthy");
}
if (42) {
    console.log("Numbers other than 0 are truthy");
}
if ([]) {
    console.log("Empty arrays are truthy");
}
if ({}) {
    console.log("Empty objects are truthy");
}

Practical Use Cases

Default Values with Logical OR (||)

Example:

let name = "";
let defaultName = name || "Guest";
console.log(defaultName); // Outputs: Guest

Checking for Empty Objects or Arrays

Even though [] and {} are truthy, you may want to check if they contain values.

let obj = {};
if (Object.keys(obj).length === 0) {
    console.log("Object is empty");
}

Avoiding Unnecessary Comparisons

Instead of writing:

if (value !== null && value !== undefined && value !== "") {

You can simplify it using:

if (value) {

This works as long as 0 and false are acceptable values.

Conclusion

Understanding truthy and falsy values in JavaScript helps in writing cleaner, more concise code. By using these concepts, you can simplify conditionals, set default values efficiently, and write more readable programs. Give a try to examples above and let me know if it improves your JavaScript programs!

JavaScriptBeginnerFoundationsTruthyFalsy
Avatar for Roger O'Donnell

Written by Roger O'Donnell

Junior Web Developer

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.