In JavaScript, boolean is a primitive data type. true
and false
are the two reserved words that represent boolean values. You can assign true
or false
directly to the variable and constant.
let x = true; const y = false;
Boolean values are used in control structures such as if/else. JavaScript executes a set of statements if a condition is true and run another set of statements if the condition is false.
let age = 20; if(age>=18){ console.log('You can vote.'); }else{ console.log('You cannot vote.'); }
In this code, a person's age is above 18, so the condition evaluates to true
and the statement mentioned in the if
block executes.
For boolean values, the typeof
operator returns "boolean
".
let isLeapYear = false; console.log(typeof isLeapYear); //"boolean"
It is important to note that, apart from false
, six other values are considered as falsy values. Those values are:
All these six values work as false
when used with comparison, logical and other operators.
let x; if(x){ console.log(`The value of variable x is ${x}`); }else{ console.log('Variable x is not initialized'); }
In this code, variable x
is not initialized, so it has an undefined
value. From the text, you know that in JavaScript, undefined
works as false
. Therefore, a statement written inside the else
block is executed.