DEV Community

Manav Misra
Manav Misra

Posted on • Updated on

Logical Operators

&& - 'and'

&& - means 'and' and both the left-hand side and the right-hand side operands must be 'truthy' for && to be 'truthy.'

For example, if I tell my daughter that she will receive 🍦 if she gets an 'A' on her test and cleans her room, then both of those conditions must be true for her to get 🍦.

Here's how that might look in code:

const daughter = {
  name: "Lily",
  devToUsername: "@awesomecoder123"
  mostRecentTestScore: "A",
  roomStatus: "Clean"
}

if (daughter.mostRecentTestScore === "A" && daughter.roomStatus === "Clean) {

  // This will only 'log' if BOTH CONDITIONS are 'truthy'
  console.log("🍦");
}
Enter fullscreen mode Exit fullscreen mode

And, here are a couple of examples loosely referencing how this sort of thing might work in React:


&&, if the left-hand side operand is 'false-y,' then there is no reason to evaluate the right-hand side operand.

If the left-hand side operand is 'false-y,' then we shortcircuit the &&.

Using the analogy above πŸ‘†πŸ½, if my daughter didn't receive an "A," there isn't any reason to check her room with regards to 🍦.

|| - 'or'

|| - means 'or' and either the left-hand side or the right-hand side operand must be 'truthy' for || to be 'truthy.'

Using the same 'daughter analogy' πŸ‘†πŸ½, if the deal was that she could get 🍦 if either she got that "A," or she cleaned her room...

const daughter = {
  name: "Lily",
  devToUsername: "@awesomecoder123"
  mostRecentTestScore: "A",
  roomStatus: "Dirty"
}

if (daughter.mostRecentTestScore === "A" || daughter.roomStatus === "Clean) {

  // This will only 'log' even if the 'room is dirty' b/c she got the 'A' πŸ˜ƒ
  console.log("🍦");
}
Enter fullscreen mode Exit fullscreen mode

And, here's another example showing short-circuiting of an ||. This means that if the left-hand side operand is 'truth-y,' we don't bother to look πŸ‘€ at the right-hand side operand - we short-circuit the ||.


Finally, we see one somewhat more realistic example putting things back together.

Top comments (2)

Collapse
 
awesomecoder123 profile image
Lily Misra

Well where's my ice cream dad?

Collapse
 
codefinity profile image
Manav Misra • Edited

πŸ™„ We'll C what happens. If you pass the && conditional operator. ;)