Logical operators in JavaScript — how do you use them?

The name of the pictureThe name of the pictureThe name of the pictureClash 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





It should state "All values are truthful...", since i.e. undefined is a value, but there's also the variable undefined which holds this value, by default. Also NaN is not equal to anything, not even to itself.
– Ivo Wetzel
Dec 26 '10 at 22:33


undefined


undefined


NaN





@Ivo: 1: Fixed. 2: That's irrelevant; !NaN is true, so NaN is falsy.
– SLaks
Dec 26 '10 at 22:38


!NaN


true


NaN





Still NaN == NaN is false. So it's still a special case from the above list one might think that NaN works like every other falsy value.
– Ivo Wetzel
Dec 26 '10 at 23:33





@Ivo: SLaks is only listing JavaScript's falsy values. He isn't claiming anything else about NaN or any of the other values.
– Sasha Chedygov
Dec 26 '10 at 23:40


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


!





What about document.write("Cat"||"Dog")?
– DarkLightA
Dec 26 '10 at 22:27


document.write("Cat"||"Dog")





@DarkLightA: I'd suggest that you don't write code like that! It causes implicit conversions and it will confuse everyone.
– Mark Byers
Dec 26 '10 at 22:31







Okay, it was in MDC :D
– DarkLightA
Dec 26 '10 at 22:39





It shouldn't confuse anyone. Short-circuiting has been a common idiom in javascript since around 5 years ago. Crockford calls || the default operator so "Cat" || "Dog" should read cat, defaults to dog. Personally I read it as cat, otherwise dog.
– slebetman
Dec 27 '10 at 0:33


||


"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.

Popular posts from this blog

Keycloak server returning user_not_found error when user is already imported with LDAP

PHP parse/syntax errors; and how to solve them?

How to scale/resize CVPixelBufferRef in objective C, iOS