4 ms·
var undefined = "raspberry"; function eatFruit (fruit) { if (fruit === undefined) { fruit = "strawberry"; } ... }
by chrisdew 11y ago
var undefined = "raspberry";
function eatFruit (fruit) {
if (fruit === undefined) {
fruit = "strawberry";
}
...
}
eatFruit("raspberry");
- robinson7d 11y agoNot that I agree with the sentiment of the article (defaulting with || is usually okay!), but hopefully people reading these pieces, and worrying about such things, are already using strict mode.
- tracker1 11y agoyou can also use... if (foo === void 0) ... //or var undef; ... if (foo === undef) ...
- kcorbitt 11y agoI was intrigued and just tried this. It doesn't work (at least in the chrome console) -- "undefined" is a reserved keyword and while the interpreter doesn't complain about attempting to assign it the value of "raspberry," it appears to ignore the statement.
- chrisdew 11y agoApologies, you're right. I'm sure this used to work, a few years ago... but I may be getting old.
- chrisdew 11y agoBut there's definitely still odd stuff here: $ node > var bar = undefined = "foo"; undefined > bar 'foo' > undefined undefined >
- deleted 11y ago[deleted]
- seba_dos1 11y ago"undefined" (and "NaN") are not a reserved keywords. They're just a properties of global object, with values of, respectively, primitive "undefined" and primitive "NaN" (which are not accessible directly). In ES5 these properties are defined as [[Writable]]: false, which explains your behaviour. You can however still create such variable in non-global scope - simply wrap that code in a function and it will work.