Data Types in JavaScript : Boolean

Boolean has only two values in any programming language True & False. It decides if the expression is true or false in if-else, while, for-loop blocks and according to that certain part of code gets executed.

Boolean in if-else Condition

Example:

‎
let num = 22;

if(num === 22) {
    console.log('Value is 22. This is TRUE');
}
else {
    console.log('Value is NOT 22. This is FALSE');
}
‎

In the above code, expression inside if condition will return Boolean value true or false. We can see that value of num is 22. So in the if condition expression will return True because we are checking for value 22.

Note: Read about triple equals (===).

Boolean in while Loop

Example:

‎
let i = 0;

while(i <= 5) {
    console.log(i + " is less than OR equal to 5. This is TRUE");
    i++;
}

console.log(i + " is more than 5. This is FALSE");
‎

In the above while loop example, we have declared variable i value to 0. In the while expression we are checking if value of i is less than or equal to 5. Till value of i is less than 5 (Means Boolean expression will return true) that while loop block will execute and when value of i will go above 5, while loop will terminate because expression will return false and console log outside while loop will get execute.

Note: We are incrementing value of i in the while loop.

Boolean in for Loop

Example:

‎
for(i = 0; i <= 3; i++)
{
    console.log(i + " is less than OR equal to 3. This is TRUE");
}
console.log(i + " is more than 3. This is False");
‎

For loop expression is also work similar as while loop. Block of for loop will execute till value of i is less than or equal to 3. Once value goes above 3, for-loop will get terminated and console log outside message will be printed.

Explicit use of Boolean

All above ways we have used Boolean invisibly/internally/implicitly. You can make use of Boolean data type explicitly also. Lets see the example.

‎
let flag = true;

if(flag) {
    console.log("Flag Spotted");
}
‎

In some cases you don’t have expression but still you want to execute code according to some indication or flag. In that case you can directly declare variable and give it true or false value and use that variable wherever required.

This is how Boolean data type plays very important role in JavaScript expressions.

Categories js