DEV Community

Cover image for JavaScript: Boolean Basics
kymiddleton
kymiddleton

Posted on • Updated on

JavaScript: Boolean Basics

Booleans

Booleans, as a primitive data type, do not have methods and are not objects. Booleans are mostly correlated with conditional statements and come into play when a data type is needed that can only have one of two values such a True / False, Yes / No, or On / Off.

const YES = true;
const NO = false;

Conditional statements can be used to determine different actions based on specific conditions. If statements and if…else statements form the most common conditional statements in JavaScript and generally run code only if a condition is true.

if (YES) {
  alert (Block of code will execute)
} 
if (NO) {
  alert (This block of code will NOT execute)
}

If there is a need to check for more than one condition the else if statement can be used which goes between if and else. The condition tells JavaScript what to check for before continuing. If the condition evaluates true the code in the if block executes. If the condition is false the code in the else block executes.

if (condition) {
  //Do Something
} else {
  //Do Something Else
}}

Comparison Operators

Comparison operators are used to test for true or false and are used in logical statements to determine equality between values or variables.

For Comparing Numbers:

Greater than > or greater than or equal to >=

6 > 4 // True
6 > 4 // False
6 >= 6 //True

Less than < or less than or equal to <=

6 < 8 // True
6 < 6 // False
6 <=6 //True

To check if items are equal or unequal:

In JavaScript a triple equals === is referred to as strictly equal and evaluates if the two numbers are equal. A double equals == is used to see if two values are the same. The unequal operator != returns true if the items are not equal. The non-identity or strictly unequal !== returns true if the items are NOT equal and/or not the same type.

Equal === or unequal !=

6 === 6 // True
6 != 6 // False

Strictly unequal !== or unequal !=

1 != 2 // True
4 !== 3 // True

Strictly equal === or equal ==

6 === 6 // False
6 == 6 // True

When comparing a string ‘6’ versus the number 6 the double equals == evaluates to true whereas the triple or strictly equal === evaluates to false.

However there can be confusion about equality so beware! Values being referenced in a Boolean context to a Boolean value can be coerced automatically in JavaScript.

The following evaluate to True:

console.log (‘’ == 0);
console.log (null == undefined);
console.log (false == 0);

What about these?

if ( [ ] )  / / if ( { } ) / / 

A guess of True would be correct but why? Despite being empty, [ ] and { }, both of these are objects. Any object, in JavaScript, will be coerced to a Boolean value of true. To avoid type coercion use === and !== to compare two things.

Top comments (0)