-2

I was coding in node, so I got an error, will you explain this error to me?

When I write a statement console.log(Email||Password||Song)
It's returning the value of Email variable.


But when I write statement console.log(!Email||!Password||!Song);
It's returning actual value which is true/false

Can you Please explain me
  • I found this video very helpful in understanding logical operators, may help you as well: https://www.youtube.com/watch?v=MHpLGco_jSk&list=PLaZSdijfCCJDm33pC1WX56jTW1r9Ln1EG&index=20 – Inzamam Malik Oct 25 '22 at 15:55

1 Answers1

0

So, first up the or (||) operator:

a || b === a if a is truthy, otherwise b

So the or operator isn't strictly useful for boolean types. For example, you could set a default value for data like

function makePerson(name, age) {
  return { name: name, age: age || 0 }
}

Next, the not (!) operator:

!a === false if a is truthy, true otherwise

So note that the ! operator strictly provides boolean outputs.

So with your example,

Email||Password||Song

will be Email if truthy, then Password if truthy, and finally Song

!Email||!Password||!Song

is going to end up evaluating to something like

false||false||true

or

true||false||false

etc. By adding in the unary not, you're effectively casting all your inputs to booleans, and the output of the or operator is the type of its inputs.

CollinD
  • 7,304
  • 2
  • 22
  • 45