On Monday, 18 April 2011 17:01:04 UTC-3, Angus Croll wrote:
>
> Hey JR
>
> He didn't say If (foo) { } is the same as if (foo !== 'undefined') { }
> He said If (foo) { } is the same as if (foo != 0) { }
>
> ( page 121 of The Good Parts)
>
>
Hi Angus,
In that (good) part of the book, Douglas Crockford was talking about type
coertion. So the == and != operators stepped in this thread, because they do
type coertion. Douglas is correctly saying that if you want type coertion,
then use if (foo) instead of if (foo != 0) for instance. But is could be:
if (foo != undefined) - in the case you are testing for a variable not
initialised yet.
DG is trying to show that == and != operators are bad because they can mask
type errors.
On top of that, we can use " if (foo) { } " as an alias whenever we need to
test for: undefined, null, NaN, 0, "" (empty string) and, of course, false,
because these values will make the test be false, according to the ECMA-262
3rd edition.
> The former case uses toBoolean the latter uses toPrimitive
>
> therefore:
>
> var foo = [0];
> console.log(foo ? true : false) //true
>
This is an expected behaviour, working as designed by the specification,
because [0] is an Array. It is the same as:
var foo = [0];
if (foo) {
return true;
} else {
return false;
}
> console.log(foo != 0 ? true : false) //fal
>
>
You are doing exactly what Douglas is saying to avoid: type coertion by
means of the != operator. Instead of doing that, use simply "if (foo)..."
Cheers,
João Rodrigues (JR)
--
To view archived discussions from the original JSMentors Mailman list:
http://www.mail-archive.com/[email protected]/
To search via a non-Google archive, visit here:
http://www.mail-archive.com/[email protected]/
To unsubscribe from this group, send email to
[email protected]