0
0
Javascriptprogramming~5 mins

Logical operators in Javascript

Choose your learning style9 modes available
Introduction

Logical operators help you make decisions by combining or changing true/false values.

Checking if a user is logged in AND has admin rights before showing a page.
Allowing access if a user is a member OR has a special invite.
Making sure a value is NOT empty before using it.
Combining multiple conditions to control program flow.
Stopping checks early if one condition is false to save time.
Syntax
Javascript
condition1 && condition2  // AND
condition1 || condition2  // OR
!condition               // NOT

AND (&&) returns true only if both conditions are true.

OR (||) returns true if at least one condition is true.

NOT (!) flips true to false and false to true.

Examples
AND returns false because one condition is false.
Javascript
const a = true && false;  // false
OR returns true because one condition is true.
Javascript
const b = true || false;  // true
NOT flips true to false.
Javascript
const c = !true;           // false
OR inside NOT: OR is true, NOT flips it to false.
Javascript
const d = !(false || true); // false
Sample Program

This program checks if a user is logged in and if they are an admin. It shows different messages based on these conditions.

Javascript
const isLoggedIn = true;
const isAdmin = false;

if (isLoggedIn && isAdmin) {
  console.log('Show admin panel');
} else if (isLoggedIn && !isAdmin) {
  console.log('Show user dashboard');
} else {
  console.log('Please log in');
}
OutputSuccess
Important Notes

Logical operators work with values that are true or false, but JavaScript also treats other values as true or false (called truthy and falsy).

Use parentheses to group conditions clearly and avoid confusion.

Short-circuiting: AND stops checking if the first is false; OR stops if the first is true.

Summary

Logical operators combine or change true/false values to help make decisions.

AND (&&) needs both true, OR (||) needs one true, NOT (!) flips true/false.

They are useful for controlling what your program does based on multiple conditions.