Introduction to Boolean in JavaScript

javascript booleans introduction
10 November 2024

In the programming language JavaScript, there exists a data type called Boolean, which is used to represent two possible states: true or false. This data type is commonly used in situations where logical conditions are required, and it is quite useful for making decisions. For example, when you want to enforce a condition like "Is the user logged in?", you implement it using Boolean.

Boolean variables are ideal for decision-making in code. For instance, you can use Boolean conditions to display or hide page elements or execute different functions based on a condition.

In JavaScript, you can use conditional expressions to check the values of Boolean variables. As shown in the example below, you can determine whether a block of code should execute or not:

Moreover, many logical operations such as "equals" (==) and "not equal" (!=) can work with Boolean values. This functionality allows you to incorporate more complex logical expressions into your code.

Many internal and organized JavaScript functions also return Boolean values, such as methods related to checking if the solution to a problem is correct or checking the state of a tree node. Below is a practical example:


<script>
  let isLoggedIn = true;
  let isUserAdmin = false;
  
  if (isLoggedIn) {
    console.log('User is logged in');
  }
  
  if (!isUserAdmin) {
    console.log('User is not an admin');
  }
</script>


let isLoggedIn = true;
In this line, a variable called isLoggedIn is defined with an initial value of true, indicating that the user is logged in.



let isUserAdmin = false;
Here, a variable named isUserAdmin is defined with a value of false, indicating that the user does not have admin access.



if (isLoggedIn) {
This checks whether the user is logged in or not using an if statement.



console.log('User is logged in');
If the user is logged in, this message will be displayed in the console.



if (!isUserAdmin) {
Using the negation symbol (!) means "not" and checks if the user is not an admin.



console.log('User is not an admin');
In this case, if the user does not have admin access, this message will be displayed in the console.


FAQ

?

How can I use Boolean in JavaScript?

?

Can I perform more complex logical operations with Boolean?