Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.javascript > #20909
| From | "Joao Rodrigues (J.R.)" <groups_jr-1@yahoo.com.br> |
|---|---|
| Newsgroups | comp.lang.javascript |
| Subject | Re: falsy and truthy |
| Date | 2013-08-10 09:03 -0300 |
| Organization | Aioe.org NNTP Server |
| Message-ID | <ku5a5r$h4j$1@speranza.aioe.org> (permalink) |
| References | <f80d266d-dad8-4514-a617-773dec591a52@googlegroups.com> |
On 06-07-2013 00:01, tlbaxter99@yahoo.com wrote:
> Hi everyone,
>
> I thought I understood falsy and truthy until I ran this code:
>
> var falsyValues = [false, 0, null, "", undefined, NaN];
>
> for (var index in falsyValues)
> if (!falsyValues[index])
> console.log("FALSE");
> else
> console.log("TRUE");
>
> As I expected, "FALSE" was printed for all 6 values. No problem.
As described in ES 5.1, ยง9.2 (ToBoolean), there are seven falsy values:
false, 0, -0, "", NaN, null, and undefined. All other values are truthy.
Logical NOT (!) (!expr) returns false if its single operand can be
converted to true; otherwise, returns true.
>
> Now, when I modify the if() statement to this:
> if (false == falsyValues[index])
>
> I see that null, undefined and NaN do NOT compare as being equal to false, yet when using the not operator(!) a shown earlier, they ARE considered false.
>
> Can someone explain this? Using the not operator (!) is apparently not the same as comparing directly against false.
In this particular case, we should use the strict Equals Operator (===)
than just the Equals Operator (==), because undefined == null, for
instance, produces true, whereas undefined === null yields false.
These are some interesting cases:
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true
' \t\r\n ' == 0 // true
Note: Douglas Crockford's advice is to never use [what he calls] the
evil twins (== and !=). Instead, we should always use === and !==,
although Crockford's advice is a tad exaggerated when dealing with the
typeof operator which always returns a string value.
--
Joao Rodrigues (J.R.)
Back to comp.lang.javascript | Previous | Next — Previous in thread | Find similar | Unroll thread
falsy and truthy tlbaxter99@yahoo.com - 2013-07-05 20:01 -0700
Re: falsy and truthy Denis McMahon <denismfmcmahon@gmail.com> - 2013-07-06 07:20 +0000
Re: falsy and truthy Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2013-07-06 10:24 +0200
Re: falsy and truthy "Evertjan." <exxjxw.hannivoort@inter.nl.net> - 2013-07-06 11:22 +0200
Re: falsy and truthy "Joao Rodrigues (J.R.)" <groups_jr-1@yahoo.com.br> - 2013-08-10 09:03 -0300
csiph-web