Skip to content

JavaScript Boolean variable | Basics

  • by

Use var or let or const keyword to create Boolean variable in JavaScript. A boolean variable is used to identify whether a condition is true or false.

Accordingly, boolean values can only assume two values:

  1. true
  2. false
let exampleBoolean = true;
let anotherExample = false;

Note: Never create a boolean using the Boolean constructor function. Instead, just use the literal values, true or false.

JavaScript Boolean variable

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    var age = 0;

    // bad
    var hasAge = new Boolean(age);
    console.log(hasAge)

    // good
    var hasAge = Boolean(age);
    console.log(hasAge)

    // good
    var hasAge = !!age;
    console.log(hasAge)

    // good
    var hasAge = !age;
    console.log(hasAge)

  </script>
</body>
</html>

Output:

JavaScript Boolean variable

More Code

// falsy values: false, 0, -0, 0n, null, undefined, NaN, and the empty string ""
console.log(Boolean(false)) // false
console.log(Boolean(0)) // false
console.log(Boolean(-0)) // false
console.log(Boolean(0n)) // false
console.log(Boolean(null)) // false
console.log(Boolean(undefined)) // false
console.log(Boolean(NaN)) // false
console.log(Boolean("")) // false
console.log(typeof Boolean("")) // boolean

// truthy values: true, 1, -1, 1n, -1n, Infinity, -Infinity, " ", {}, []
console.log(Boolean(true)) // true
console.log(Boolean(1)) // true
console.log(Boolean(-1)) // true
console.log(Boolean(1n)) // true
console.log(Boolean(-1n)) // true
console.log(Boolean(Infinity)) // true
console.log(Boolean(-Infinity)) // true
console.log(Boolean(" ")) // true
console.log(Boolean({})) // true
console.log(Boolean([])) // true
console.log(typeof Boolean([])) // boolean

How to change a boolean value in JS?

Answer: To change a boolean to its opposite value you can use negation (!), for example x = !x means “set x to false if it’s truthy or to true if it’s falsy”.

<script>
        let testBool = true;
        console.log(testBool);
      
        function toggle() {
            testBool = !testBool;
            console.log(testBool);
        }
</script>

Do comment if you have any doubts or suggestions on this JS variable topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.