[JavaScript] Basics of Booleans and Complete Guide to Truthy/Falsy Evaluation

目次

Overview

In JavaScript, the “Boolean” data type is the most basic element for determining the control flow of a program. Beyond simple true / false judgments, understanding the concept of “Truthy” (values treated as true) and “Falsy” (values treated as false) is essential for writing robust conditional logic. This article explains how to use comparison operators, implicit type conversion in if statements, and techniques for converting values to booleans using the logical NOT operator (!).

Specifications (Input/Output)

  • Input: Any data such as numbers, strings, arrays, or objects.
  • Output:
    • Boolean results from comparison operations.
    • Existence check results via if statements.
    • Results of conversion to Boolean type using ! and !! operators.

Basic Usage

In JavaScript, booleans are used in the following scenarios:

  • Comparison Operations: Results like 10 < 20 generate true or false.
  • Conditional Checks: Used in if (value) to determine if a piece of data exists or is valid.
  • Logical Negation: Use !value to flip the boolean state, or !!value to force a value into a Boolean type.

Full Code (HTML / JavaScript)

HTML (index.html)

This is a simple console screen to verify the results.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Boolean Logic Demo</title>
    <script src="boolean-demo.js" defer></script>
</head>
<body>
    <div class="container">
        <h1>Please check the Console</h1>
        <p>Verification results for Boolean logic and Truthy/Falsy values are displayed in the console.</p>
    </div>
</body>
</html>

JavaScript (boolean-demo.js)

This implementation covers three patterns: comparison, existence checks, and type conversion.

/**
 * Demonstration of Boolean values and logical operators
 */
const runBooleanDemo = () => {
    console.log('--- 1. Judgment by Comparison Operators ---');
    
    const limit = 10;
    const current = 20;

    // Comparison (Result is always true or false)
    console.log(`current < limit: ${current < limit}`); // false
    console.log(`current > limit: ${current > limit}`); // true


    console.log('--- 2. Judging Truthy and Falsy Values ---');
    
    // String judgment
    // An empty string "" is Falsy; anything else is Truthy
    const userName = "AdminUser";
    const userBio = ""; // Empty string

    if (userName) {
        console.log(`User name found: ${userName}`); // This will run
    }

    if (userBio) {
        console.log("Bio found");
    } else {
        console.log("No bio (Empty string is Falsy)"); // This will run
    }

    // Environment detection (Checking for a string in UserAgent)
    // .includes() returns a boolean
    const userAgent = navigator.userAgent;
    const isIphone = userAgent.includes("iPhone");
    
    if (isIphone) {
        console.log("Accessing from an iPhone");
    } else {
        console.log("Accessing from a non-iPhone device");
    }


    console.log('--- 3. Logical Negation (!) and Boolean Casting (!!) ---');
    
    // A single ! is "negation"
    const hasError = false;
    console.log(`!hasError: ${!hasError}`); // true

    // A double !! is "casting to Boolean type"
    // Converts to true if a value exists, or false if it is empty or zero
    console.log(`!!"Hello": ${!!"Hello"}`); // true
    console.log(`!!123: ${!!123}`);         // true
    console.log(`!![1, 2]: ${!![1, 2]}`);   // true (Arrays are Truthy even if empty)
    
    console.log(`!!0: ${!!0}`);             // false (0 is Falsy)
    console.log(`!!undefined: ${!!undefined}`); // false
};

// Execute
runBooleanDemo();

Customization Points

  • Understanding Falsy Values: In JavaScript, the values considered “false” are strictly defined. Memorizing these will help prevent bugs:
    • false
    • 0 (Numerical zero)
    • "" (Empty string)
    • null
    • undefined
    • NaN (Not a Number)
  • Using the Boolean() Function: Writing !!variable is synonymous with Boolean(variable). If you prioritize readability, using Boolean() is a good choice.

Important Points

  • The Trap of Arrays and Objects: An empty array [] or an empty object {} is treated as Truthy in JavaScript. You cannot check if data is empty using if ([]). To check if an array has no items, use array.length === 0.
  • “0” (String Zero): While the number 0 is Falsy, the string "0" is Truthy. Be careful when handling values from form inputs, as they are often treated as strings.
  • Strict Comparisons: While if (flag) is convenient, it treats 0 as false. If you need to treat 0 as a valid value, you should write an explicit check like if (value !== null && value !== undefined).

Advanced Usage

Short-circuit Evaluation

This is a technique to set a “default value” using logical operators like || or ?? when a variable is Falsy.

// If userBio is an empty string (Falsy), "Not set" is assigned
const displayBio = userBio || "Not set";

// Nullish Coalescing Operator (ES2020)
// Assigned "Guest" only if the value is null or undefined (treats 0 or "" as valid)
const displayName = inputName ?? "Guest";

Summary

In JavaScript’s conditional branching, every value is classified as either “Truthy” (true-like) or “Falsy” (false-like). Understanding that 0, "", null, and undefined are Falsy, while [] (empty array) is Truthy, will help you significantly reduce unexpected judgment errors.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次