- 2008-12-26 (Fri) 10:53
- JavaScript
This entry is a note from “JavaScript: The Good Parts” on page 106, Appendix A: Awful Parts.
Falsy Values
In JavaScript, following values are considered as “false” when they come to conditional expression.
| Type | Value |
|---|---|
| number | 0 |
| number | NaN |
| string | ""(empty string) |
| boolean | false |
| Object | null |
| undefined | undefined |
You must have understood them already, but it’s good to have it organized.
In most of languages, String and Array is very similar. I mean, both instances have a length property for nature and you can access stored values by their own indexes. So I was wondering, if an empty string is falsy, why not an empty array is? No, an empty array is not falsy. I guess its because an array is acutally an object. Try typeof operator with one.
Here, I tried to evaluate an array with JavaScript’s nature, duck typing, but well, it doesn’t work as I imagined.
var a = []; console.log( a ? 'true' : 'false'); //of course, true; console.log( (String.prototype.constructor.apply(a)) ? 'true' : 'false'); //Oh? false... so..? var b = ['b']; console.log( (String.prototype.constructor.apply(b)) ? 'true' : 'false'); //still false...
Any value, even if it’s a string type of a String wrapper object, passed to string constructor makes an empty string.
String.prototype.constructor(['a']);
will do more as what you can imagine. String.prototype.constructor will run .valueOf() on the argument.
Comments:0
Trackbacks:1
- Trackback URL for this entry
- http://blog.nydd.org/2008/12/falsy-values-%e2%80%9cjavascript-the-good-parts%e2%80%9d/trackback/
- Listed below are links to weblogs that reference
- Falsy values – “JavaScript: The Good Parts” from Vantage Point of Queens
- pingback from Zero is ‘falsy’ in JavaScript « Bitesize Bugs 09-02-05 (Thu) 11:43
-
[...] Falsy values – extract from “JavaScript: The Good Parts” Truthy and falsy in JavaScript [...]