Menu
Coddy logo textTech

Logical Operators Part 3

Part of the Fundamentals section of Coddy's JavaScript journey — lesson 21 of 77.

When working with logical expressions, sometimes we need to simplify or rearrange them.

! (not) in front of two conditions joined by && (and), you can split it into two separate parts. The && (and) becomes || (or), and each part gets its own ! (not):

!(A && B) is the same as (!A) || (!B)

For example:

// Let's check if a number is NOT (between 1 and 10)
let number = 15

// These two expressions are equivalent:
let result1 = !(number >= 1 && number <= 10)
let result2 = !(number >= 1) || !(number <= 10)

console.log(result1)  // True
console.log(result2)  // True

The opposite is also correct: !(A || B) is the same as (!A) && (!B)

For example:

// Checking if a person is NOT (a student or employed)
let is_student = false
let is_employed = false
// These two expressions are equivalent:
let result1 = !(is_student || is_employed)
let result2 = !is_student && !is_employed

console.log(result1)  // True
console.log(result2)  // True
challenge icon

Challenge

Beginner

You're helping a pet shop create a system to determine if they can sell a pet to a customer.

initialize the following variables:

  • has_license with the value true
  • has_space with the value false
  • has_experience with the value true

Write the following logical expressions to determine if:

  • can_sell_regular_pet: Customer needs EITHER a license OR experience, AND must have space
  • can_sell_exotic_pet: Customer needs BOTH a license AND experience, AND must have space
  • cannot_sell_any_pet: Customer has NO license AND NO experience, OR has NO space

Cheat sheet

De Morgan's Laws allow you to simplify logical expressions by moving the ! (not) operator:

!(A && B) is the same as (!A) || (!B)

// NOT (between 1 and 10)
let result1 = !(number >= 1 && number <= 10)
let result2 = !(number >= 1) || !(number <= 10)  // equivalent

!(A || B) is the same as (!A) && (!B)

// NOT (student or employed)
let result1 = !(is_student || is_employed)
let result2 = !is_student && !is_employed  // equivalent

Try it yourself

// Initialize variables

// Calculate conditions
let can_sell_regular_pet = 
let can_sell_exotic_pet = 
let cannot_sell_any_pet =

// Don't delete the lines below
console.log("Can sell regular pet:", can_sell_regular_pet)
console.log("Can sell exotic pet:", can_sell_exotic_pet)
console.log("Cannot sell any pet:", cannot_sell_any_pet)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals