Khachatryan-dev

Boolean Values in JavaScript

Boolean Values in JavaScript — Truthy and Falsy Values

Aram
Khachatryan

Boolean Values in JavaScript — Truthy and Falsy Values




Description


In this article, we will explore Boolean values in JavaScript in detail: how they work, which values are considered truthy or falsy, and how to use them effectively in programming.




Core Content


What is a Boolean?


The Boolean type in JavaScript has only two possible values:


  • true
  • false

These two values are used in conditional statements, loops, and other logical operations.


    const isLoggedIn = true;
    const hasAccess = false;

Truthy vs Falsy Values


In JavaScript, certain values are automatically converted to Booleans when required. These values are called "truthy" or "falsy".


Falsy Values


These values are considered equivalent to false in Boolean contexts:


    // These values are falsy:
    false
    0
    -0
    0n // BigInt zero
    "" // empty string
    null
    undefined
    NaN

Example:


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

Truthy Values


All other values are considered truthy, meaning they evaluate to true.


    // Examples:
    "Hello"
    42
    []
    {}
    function () {}

    if ("hello") {
      console.log("Strings are truthy");
    }

The Boolean() Function


You can explicitly convert a value to a Boolean using the Boolean() function.


    Boolean(0); // false
    Boolean("text"); // true

Or use the shorthand:


    !!value // Double NOT operator to coerce to Boolean

    console.log(!!"abc"); // true
    console.log(!!null);  // false

Where Are Booleans Used?

  • In conditions for if, else if, while, for
  • Building logical expressions
  • Interacting with APIs
  • Conditional rendering of components
5.00 / 1
Buy me a coffee
  • 0
  • 15

Discover More Content

Comments
No data
No comments yet. Be the first to comment!
Leave a Comment
You must be logged in to leave a comment.Login