Logical Operators

  • Working with conditions means using booleans, true or false values. In JavaScript there are operators that work with boolean values known as logocal operators.

  • There are three logical operators:

    • the and operator &&

    • the or operator ||

    • the not operator, otherwise known as the bang operator !

&& operator:

When using && operator, we are checking both sides to evaluate to true for the entire condition to evaluate to true and execute, otherwise the else block will execute.

Example:

If (stopLight === 'green' && pedestrains === 0) {
	console.log('Go!');
} else {
	console.log('Stop');
}

Example:

let sale = true;

sale = false;

if(sale) {
  console.log('Time to buy!');
} else {
  console.log('Time to wait for a sale.');
}

// Output: not bed time yet

|| operator:

When using the || operator only one side of condition needs to be true for the overall statement to evaluate to true.

Example:

if (day === 'Saturday' || day === 'Sunday') {
	console.log('Enjoy the weekend!');
} else {
	console.log('Do some work.')
}

! operator:

The ! not operator reverses or negates the values of a boolean.

Example:

let excited = true;
console.log(!excited);

// Output: false

let sleepy = false;
console.log(!sleepy);

// Output: true

Last updated