Booleans in JavaScript

Welcome to the world of truth or falsehood! This chapter dives deep into booleans, the fundamental building blocks of logical reasoning in JavaScript. We'll explore their role in decision-making, conditional statements, and how they interact with other data types. By the end, you'll be a master of boolean logic in your JavaScript programs.

What are Booleans?

  • Booleans are data types that represent only two possible values: true or false.
  • They act like tiny switches, indicating whether a condition is met or not.

Declaring Booleans:

You can explicitly assign true or false to a variable:

				
					let isLoggedIn = true;
let isNightTime = false;

				
			

Using Booleans in Conditional Statements:

Booleans shine in conditional statements like if, else if, and else:

				
					if (isLoggedIn) {
  console.log("Welcome back!");
} else {
  console.log("Please log in.");
}

				
			
  • The if statement checks if isLoggedIn is true.
  • If it is, the code within the if block executes (prints “Welcome back!”).
  • If isLoggedIn is false, the else block executes (prints “Please log in.”).

Comparison Operators:

We use comparison operators (==, !=, ===, !==, <, >, <=, >=) to compare values and generate boolean results:

				
					const age = 25;
const isAdult = age >= 18; // True (age is 25, which is greater than or equal to 18)

const password = "secret123";
const isCorrectPassword = password === "secret123"; // True (strict comparison: value and type must match)

				
			
  • JavaScript sometimes converts other data types to booleans in certain contexts:

    • Numbers:
      • Non-zero numbers are considered true.
      • Zero (0), NaN (Not a Number), and -Infinity are considered false.
    • Strings:
      • An empty string ("") is considered false.
      • Any non-empty string is considered true.
    • null and undefined:
      • Both are considered false.
    • Objects and Arrays:
      • Any non-empty object or array is considered true.
      • An empty array ([]) or object ({}) is considered false.

Example:

Logical Operators:

Booleans can be combined using logical operators (&& – AND, || – OR, ! – NOT) to create more complex conditions:

				
					const hasPermission = true;
const isWeekend = false;

if (hasPermission && !isWeekend) { // AND: both conditions must be true
  console.log("You can access the resource.");
} else {
  console.log("Access denied.");
}

const hasCoupon = false;
const isMember = true;

if (hasCoupon || isMember) { // OR: at least one condition must be true
  console.log("You qualify for a discount!");
} else {
  console.log("No discount available.");
}

				
			

Initializing Variables:

  • const hasPermission = true;: This declares a constant variable named hasPermission and assigns it the boolean value true.
  • const isWeekend = false;: This declares another constant variable named isWeekend and assigns it the boolean value false.
  • const hasCoupon = false;: This declares a constant variable named hasCoupon and assigns it the boolean value false.
  • const isMember = true;: This declares a constant variable named isMember and assigns it the boolean value true.

First Conditional Statement (AND):

  • if (hasPermission && !isWeekend) { ... }: This checks for two conditions using the AND operator (&&):
    • hasPermission: This condition is true.
    • !isWeekend: This applies the NOT operator (!) to isWeekend, effectively checking if it’s not the weekend. Since isWeekend is false!isWeekend is true.
  • Both conditions need to be true for the code within the if block to execute. In this case, they are both true, so the code proceeds:
    • console.log("You can access the resource.");: This prints the message “You can access the resource.” to the console.

Second Conditional Statement (OR):

  • if (hasCoupon || isMember) { ... }: This checks for two conditions using the OR operator (||):
    • hasCoupon: This condition is false.
    • isMember: This condition is true.
  • At least one of the conditions needs to be true for the code within the if block to execute. In this case, isMember is true, so the code proceeds:
    • console.log("You qualify for a discount!");: This prints the message “You qualify for a discount!” to the console.

Summary:

The code effectively implements two conditional checks:

  1. It grants access to a resource if the user has permission and it’s not the weekend.
  2. It offers a discount if the user has a coupon or is a member.

Key Points:

  • Boolean variables hold either true or false values.
  • Logical operators (&&||!) combine boolean values to create complex conditions.
  • Conditional statements (ifelse) control code execution based on boolean conditions.

Booleans are the foundation of logical decision-making in JavaScript. By mastering their core concepts, comparison operators, and logical combinations, you can write well-structured and dynamic programs that respond based on various conditions. Remember, booleans offer a simple yet powerful way to control the flow of your code! Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India