r/javascript • u/kandetta • Jul 09 '15
Don't use || to set default values in JavaScript
http://www.codereadability.com/javascript-default-parameters-with-or-operator/4
u/iku_19 Function.arity when Jul 09 '15 edited Jul 09 '15
A note to keep in mind that using true comparisons can be finnicky in some transpliers, since most of them do not truly distinguish between undefined and null. So calling eatFruit(null) wouldn't change null to strawberry.
null === undefined = false
undefined === null = false
undefined == null = true
false == null = false
0 == null = false
null == null = true
typeof null = "object"
typeof undefined = "undefined"
It's one of the headaches of writing a library, really you want to type check your variables
function eatFruit(fruit) {
if(typeof fruit != "string") {
fruit = "strawberry"
}
}Instances can be done in one of two ways Object.prototype.toString.call(variable) == "[object Date]" or variable instanceof Date
Both have their own caveats
document.body instanceof HTMLElement = true
document.body instanceof HTMLBodyElement = true
Object.prototype.toString.call(document.body) == "[object HTMLElement]" = false
Object.prototype.toString.call(document.body) == "[object HTMLBodyElement]" = true
console.log instanceof Object = true
edit: formatting
2
u/skitch920 Jul 09 '15
function isNull (obj) { return obj === null; } function isUndefined (obj) { // Why people overwrite 'undefined' // pre-ES5 is beyond me... return obj === void 0; } function isNullOrUndefined (obj) { return isNull(obj) || isUndefined(obj); }1
u/kenman Jul 09 '15
// Why people overwrite 'undefined' // pre-ES5 is beyond me...I've seen it, and it was only ever the result of a typo...
if (value = undefined) { ... }Of course, with linting you can avoid that entire class of problems, but linters weren't always common or convenient.
1
u/lewisje Dec 02 '15
That doesn't overwrite
undefined, but flipping it around does:undefined = value).Also, using the rules for non-strict equality (and ignoring a little issue with
document.allin modern browsers),isNullOrUndefinedcould be more easily written like this:function isNullOrUndefined(obj) { return null == obj; }The "little issue" I refer to is that
document.all, if it exists, is loose-equal tonullandundefined(but not strict-equal to either), although property accesses will still work, for compatibility with old sites designed specifically for oldIE.
8
u/alittletooquiet Jul 09 '15 edited Jul 09 '15
Well you can account for valid falsey values by using the ternary operator instead of ||, and you don't need to fill up multiple lines populating a single default value:
fruit = (fruit !== null && fruit !== undefined) ? fruit : "strawberry";
Edit: Just so we're clear, I vehemently disagree with the title of this post, and OP's assertion that we should write code for people who are too dumb or inexperienced to understand ||. Most of the time you should just use || to set default values.
3
u/cosinezero Jul 09 '15
Why on earth would you want fruit to be valid as "", false, or 0?
None of those values are more valid of a fruit than a default. Under what scenario would fruit be "" and not null? In that scenario why is the default invalid, and in THAT case why is the default not set before the value went from null/undefined to ""?
I would fail this on review. Without question, this should read:
fruit = fruit || "strawberry";
When said developer argues that || is unreadable, we will be then reviewing every if statement that developer has written to ensure he understands operators. This isn't syntactic sugar.
0
u/a-t-k Frontend Engineer Jul 09 '15
I would suggest adding a comment to improve the hereby decreased readability.
2
u/alittletooquiet Jul 09 '15
It depends on the complexity of the statement. Comments are always good when you're writing code that isn't necessarily intuitive to read, but I think the example above is a pretty straightforward and readable.
I'd probably switch to an if block if my conditions were too complex to quickly grasp in a ternary statement though.
1
0
Jul 09 '15
[deleted]
3
u/alittletooquiet Jul 09 '15
You can pass a variable to a function without knowing the value of that variable. If you're passing the result of another function that might return null, you need to account for null.
Just use || if you want. I do it all the time. I was just pointing out there are other ways to account for passing useful falsey values if it's an issue.
3
u/ThinkingCrap Jul 09 '15
Come on, that is common practice and everybody knows what it does.
And usual you want to catch the falsey values anyway. Take your example, why would you want to allow to eat the fruit ""?
Better readability? Not really IMHO
2
2
u/scootstah Jul 09 '15
...
}```
WAT. Epic sauce.1
u/lewisje Dec 02 '15
This presumes support for that feature of ES6, which is far from a given: https://kangax.github.io/compat-table/es6/
Among stable server implementations, it looks like only Kinoma XS6 has full support, while the unstable Echo JS has partial support; among stable clients, only Firefox has any support at all, while the WebKit nightlies have full support, and the latest Chromium builds have support behind a flag.
Also, no compiler or transpiler in the list has full support: Babel with core-js comes closest, lacking only support for default parameters in the
Functionconstructor.Fortunately, platforms with any support for default parameters also support turning explicit
undefinedarguments into the defaults, and allowing default parameters to refer to previous parameters, which is nearly everything you want with this feature.
2
Jul 09 '15
i've been using ===undefined in all of my code. I never have a problem with it. I agree with this article.
2
u/seiyria Jul 09 '15
Unfortunately it will take a while until browsers support it.
Or, you can use Babel and get this support right now.
2
2
u/x-skeww Jul 09 '15
For new code, use ES6's default function parameters.
For legacy stuff, keep using ||.
That's all there is to it, really. || is a tad cryptic for beginners, but it's the best (and most commonly used) option.
3
Jul 09 '15
I come from Python land and I love optional arguments because I can set defaults. I hate the ways to do it in JS. Yes, can't use || if I want to set something to False or 0. But the conditional is either ugly or takes up 3 lines.
2
2
u/defcon-12 Jul 09 '15
You have much bigger problems if you have to change your code to protect against devs who don't understand how || works.
14
u/a-t-k Frontend Engineer Jul 09 '15
What are your reasons?
I don't like the "mental overhead" the || operator imposes on me.
It will also eat up falsy values.
So my answer must be:
Sorry to say so, but that's rather a reason to take pity for your mental capacities than not to use the || when it seems appropriate - and I know that's not what you meant, but that's what your post inspires; which brings me to:
Know when not to use it. For example, if you want to normalize an integer value, better use the binary brother "|" instead of "||". Also, don't overuse it. If you got more than 4 lines of defaults, better use an object and whatever function to normalize to defaults. Otherwise, use || when you need it.