5 ms·
Why using : function doFoo(bar) { bar = (bar !== undefined) ? bar : "default_value"; } Over : function doFoo(bar) { bar = bar || "def
by simon_renoult 13y ago
Why using :
function doFoo(bar) {
bar = (bar !== undefined) ? bar : "default_value";
}
Over :
function doFoo(bar) {
bar = bar || "default_value";
}
Coercion avoidance ?
- 1wheel 13y ago0 is falsy in javascript; with the second method, default_value will get used instead.
- elclanrs 13y agoI'd use: bar = bar != null ? bar : 'default';
- niyazpk 13y agoYes, the second option is better in most cases. I'd spend more time reading the first one to understand what is going on compared to the second option. Keep in mind that you will have to go for the first option (or other better options) if you expect 'falsy' values to be passed as arguments.
- dagw 13y agoThe second function sets bar to "default_value" if called with a falsy argument like 0 or an empty string.