DEV Community

Manav Misra
Manav Misra

Posted on โ€ข Edited on

2

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. ;)

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay