![Creative The name of the picture]()

Clash Royale CLAN TAG#URR8PPP
Logical operators in JavaScript — how do you use them?
I don't understand how &&
, ||
, and !
work... both with bools and other data types. How do you use them?
&&
||
!
2 Answers
2
All values in Javascript are either "truthy" or "falsy".
a && b
a || b
Both operators will not evaluate any operands after the one the return.
If all operands don't match, it will evaluate to the last one.
!a
true
a
false
a
All values are truthy except the following, which are falsy:
false
+0
-0
NaN
""
null
undefined
document.all
undefined
undefined
NaN
!NaN
true
NaN
NaN
If you want to test that both of two conditions are truthy then use &&:
if (isX && isY)
{
// Do something.
}
If you want to test that one or both of two conditions are truthy then use ||:
if (isX || isY)
{
// Do something.
}
The !
inverts a boolean (a truthy value becomes false and vice versa).
!
document.write("Cat"||"Dog")
||
"Cat" || "Dog"
cat, defaults to dog
cat, otherwise dog
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
It should state "All values are truthful...", since i.e.
undefined
is a value, but there's also the variableundefined
which holds this value, by default. AlsoNaN
is not equal to anything, not even to itself.– Ivo Wetzel
Dec 26 '10 at 22:33