I don't understand how &&, ||, and ! work... both with bools and other data types. How do you use them?
2 Answers
All values in JavaScript are either “truthy” or “falsy”.
a && bevaluates to the first falsy operand,a || bevaluates to the first truthy operand.
Both operators will not evaluate any operands after the one the return. If all operands don’t match, they will evaluate to the last one.
!aevaluates totrueifais falsy andfalseifais truthy.
All values are truthy except the following, which are falsy:
nullundefinedfalse+0-0NaN0n""document.all
6 Comments
Ivo Wetzel
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.SLaks
@Ivo: 1: Fixed. 2: That's irrelevant;
!NaN is true, so NaN is falsy.Ivo Wetzel
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.
Sasha Chedygov
@Ivo: SLaks is only listing JavaScript's falsy values. He isn't claiming anything else about
NaN or any of the other values.T.J. Crowder
@Pointy - It's a quirk of web history. :-) Early on,
document.all was a Microsoft-ism and IE didn't support the fledgling DOM standard, so code would do if (document.all) { /* MS-specific code */ } else { /* DOM standard code */ }. Time moved on and A) MS implemented DOM standards, and B) Other browsers added document.all to support code that relied on it unconditionally. But the code in those pages didn't move on. To avoid having code written like that taking the Microsoft-only branch, Chrome and Firefox made document.all falsy. Eventually so did IE. It's been standardized now. :-D |
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).
3 Comments
DarkLightA
What about
document.write("Cat"||"Dog")?Mark Byers
@DarkLightA: I'd suggest that you don't write code like that! It causes implicit conversions and it will confuse everyone.
slebetman
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.