DEV Community

loading...

Logical Operators

codefinity profile image Manav Misra ・2 min read

&& - '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's another example 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 ||.


Discussion (2)

pic
Editor guide
Collapse
awesomecoder123 profile image
Lily Misra

Well where's my ice cream dad?

Collapse
codefinity profile image
Manav Misra Author

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