Skip to content

Declare Boolean in JavaScript | Basic code

  • by

Just use the literal values, true or false to declare Boolean in JavaScript. You should never create a boolean using the Boolean constructor function because new Boolean(false) returns an object.

Normally JavaScript booleans are primitive values created from literals:

let x = false;

But booleans can also be defined as objects with the keyword new:

 let y = new Boolean(false);

Keep in mind that Boolean values are case-sensitive, so true and false must be in lowercase. Additionally, JavaScript is loosely typed, meaning you can reassign values of different types to a variable. For example:

var myBoolean = true;
myBoolean = false; // Reassigning with a different Boolean value
myBoolean = "hello"; // Reassigning with a string (not recommended)

While the above is technically possible, it’s considered good practice to maintain the intended type of a variable throughout your code.

Declare Boolean in JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
    let x = false;
    let y = new Boolean(false);

    console.log(typeof(x), x);
    console.log(typeof(y), y);

  </script>

</body>
</html> 

Output:

Declare Boolean in JavaScript

Creating Boolean objects with an initial value of false

var bNoParam = new Boolean();
var bZero = new Boolean(0);
var bNull = new Boolean(null);
var bEmptyString = new Boolean('');
var bfalse = new Boolean(false);

Creating Boolean objects with an initial value of true

var btrue = new Boolean(true);
var btrueString = new Boolean('true');
var bfalseString = new Boolean('false');
var bSuLin = new Boolean('Su Lin');
var bArrayProto = new Boolean([]);
var bObjProto = new Boolean({});

Comment if you have any doubts or suggestions on this JS boolean example code.

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading