r/webdev • • Jul 10 '15

Don't use || to set default values in JavaScript

http://www.codereadability.com/javascript-default-parameters-with-or-operator/
15 Upvotes

85 comments sorted by

5

u/jxl180 Jul 10 '15

In Ruby test ||= "default" is very common, so people would think why not use it in Javascript?

2

u/Asmor Jul 10 '15

My god, I would kill for this in JS.

Not familiar with Ruby, but many perl operators can be used like that. Of particular note, //= which is like ||= except it only defaults on undef, not just any falsy value.

-7

u/alexcasalboni Jul 10 '15

Because the meaning of "default" may vary, based on the context. If you are dealing with strings you are fine 90% of cases, but if you deal with numbers or nullable parameters, you'd have to handle 0 and null differently, since || will not consider them as "acceptable values".

4

u/[deleted] Jul 10 '15

Everything in Javascript varies based on the context.

This is not an argument against using something, it's an argument in getting better developers if they can't understand such a simple concept.

1

u/alexcasalboni Jul 10 '15

Don't get me wrong, I use || in my code for default values whenever I am sure it doesn't generate conflicts.

But I am also sure that a non experienced (or just distracted) developer would easily introduce bugs, and using typeof fruit === "undefined" is so much clearer (even to backend developers during code reviews), without destroying your code elegance.

2

u/Disgruntled__Goat Jul 10 '15

non experienced developer would easily introduce bugs

But you can say that about literally every language feature. Let's not use closures in case someone doesn't understand it! Let's not use Ajax in case someone doesn't understand it!

1

u/nikrolls Chief Technology Officer Jul 11 '15

And this is precisely what code review and unit tests are for. If you don't have both then you have much larger problems than junior developers misunderstanding commonly used code patterns.

61

u/Stephen110 Jul 10 '15

I think if you're developing professionally, you and your teammates should understand when and when not to use the or operator for default arguments.

Obviously if an empty string, 0, false, or any other falsely value is a legitimate argument, you should be smart enough to default the value by other means.

26

u/_Aggron Jul 10 '15

This... Thanks for the input, Reddit thread title, but a team of competent developers shouldn't really worry about this.

11

u/drmyersii Jul 10 '15

Also have to agree here. I try my best to not use loose parameter types even in a language like JavaScript. If a function accepts strings, ints, and booleans, there might be a bigger issue.

2

u/kingNothing42 Jul 10 '15

Agree. Understanding this pattern is entry level developer stuff. Understand the language you're working in reasonably well and know when to leverage its features. I tend to treat the || initializer as standard and leave a comment whenever the code strays from that for consistency.

2

u/Asmor Jul 10 '15

Ditto.

Setting defaults makes your code cleaner and easier to write (e.g. not having to check if an object exists before checking a property of it), and setting defaults with || is much cleaner and more succinct than doing it with an if block.

I do really wish JS had an equivalent to perl's // operator (acts like || except it only returns the second value if the first value is undef instead of merely falsy). But for that matter, I really, really wish JS had C#'s ?. operator (null-propagating, i.e. foo?.bar?.baz is equivalent to (foo && foo.bar && foo.bar.baz)).

2

u/MonsieurBanana Jul 10 '15

Ecmascript6 has support for default arguments.

Nothing for that ?. operator though... Sometimes I use lodash's get and [has].(https://lodash.com/docs#has)

1

u/Asmor Jul 10 '15

Hahaha, holy shit. That's amazing. I've actually considered writing something that was exactly _.get. Can't believe it exists already. lol

I love lodash. :D

1

u/until0 Jul 10 '15

I too wish for the defined or operator in JS, but instead I just use typeof with a ternary.

1

u/schnide05095 Jul 10 '15

Perhaps I'm paranoid, but theres always some remote possibility of a function getting something unexpected. In compiled/typed languages this is not as much of an issue. But for something like JavaScript/PHP/etc I would use a ternary operator instead. That would allow for future proofing and stupid proofing all at once, without much more code.

27

u/drmyersii Jul 10 '15

If you really don't want to use the OR operator, just use ternary operators:

fruit = (typeof fruit === "undefined") ? "strawberry" : fruit;

This will allow true/false instead of truthy/falsey, and it's still pretty simple.

1

u/wevanscfi Jul 11 '15

The only thing I would add, is in passing a single object as a parameter instead of limiting your self to explicitly declared params.

function eatFruit(obj) {
     this.fruit = typeof obj['fruit'] !== 'undefined' ? obj['fruit'] : 'strawberry';
}

-4

u/msnook Jul 10 '15

but this is even less readable!

25

u/papers_ Jul 10 '15 edited Jul 10 '15

Readable to me.

Edit: I read ternary statements like this: is this true? Then x, otherwise y. it's really not hard to read at all, just syntatic sugar.

-11

u/AlmostARockstar Jul 10 '15

IT'S OK GUYS, /U/PAPERS_ CAN READ IT!

We can all rest easy now.

0

u/[deleted] Jul 10 '15

[deleted]

-14

u/AlmostARockstar Jul 10 '15 edited Jul 10 '15

(you people are fucking morons...I'm not having this useless discussion any more. Stick to your company coding practices.)

That's not the point, I can read it too.

Readability shouldn't rely on your familiarity with ternary operators and coding styles. Code that is readable should be readable to everybody.

3

u/an_actual_human Jul 10 '15

It's not at all an obscure feature.

-4

u/TiltedWit Jul 10 '15

Even my grandmother?

-6

u/AlmostARockstar Jul 10 '15

You know what I mean. Readable to everybody, within reason.

4

u/MonsieurBanana Jul 10 '15

Great, but who decides what's within reason?

A simple ternary is within reason for me.

5

u/[deleted] Jul 10 '15

Shorten it up with a helper function?

fruit = isDefined(fruit) ? fruit : "strawberry";

1

u/Stockholm_Syndrome Jul 10 '15

how is "isDefined" not native to ECMAscript hahah

1

u/Asmor Jul 10 '15

I think the real question is how is isDefined(foo) better than typeof foo === "undefined"

Seems kind of silly to me to write a function to encapsulate a single equality check.

Although I could see an argument for a default-picking function that encapsulates that whole thing.

function disOrDat(dis, dat) { return (typeof dis === "undefined") ? dis : dat; }

fruit = disOrDat(fruit, "strawberry");

2

u/BishopAndWarlord Jul 10 '15 edited Jul 10 '15

It's better because it's making your intent explicit. Source code is for humans; optimize it by making it easer for humans to understand and reason about.

  • typeof foo === "undefined"

    • What's happening on this line? Let's see ... first we have a typeof check with is right-associative, so it's checking the type of ... foo okay. Next we've got ===, which is a strict equality check. Okay, so the foo's type is being strictly compared to ... the string "undefined". Oh, I get it, this line checks whether or not foo is defined.

  • isDefined(foo)

    • What's happening on this line? We're calling a function named isDefined. That probably checks whether or not the parameter is defined. And we're passing it foo. Oh, I get it, it's checking whether or not foo is defined.

Even if the first block is "simple", it still takes more energy to understand than second version.

EDIT: Less repetition.

1

u/coloured_sunglasses Jul 11 '15

That probably checks whether or not the parameter is defined.

"Probably" is not explicit. I wouldn't know for sure until I read exactly what isDefined() does. It adds to the learning curve of your program.

Checking typeof is native JS and understandable without context.

1

u/Lystrodom Jul 10 '15

But then what happens when null is passed in?

1

u/Asmor Jul 10 '15

The same thing as if you didn't use the function and just wrote the code in line as suggested in the OP.

2

u/Lystrodom Jul 10 '15

You can change a function in one place. If you decide to change the way you check for something being defined with it inlined, you have to change it every where it's used

5

u/Stockholm_Syndrome Jul 10 '15

see, i always hear people complain about that but after just a few days of seeing it, i'm pretty sure this would become very readable to anyone.

5

u/msnook Jul 10 '15

what a perfectly appropriate user name.

-1

u/paperelectron Jul 10 '15

What? A feature that has been in C like languages since before I was born? Can't possibly expect JS developers to understand that.

2

u/msnook Jul 10 '15
if (typeof fruit === 'undefined') fruit = 'strawberry';

Shorter, no ternary, and reads like the natural language sentence that most clearly describes what it's doing, "if fruit is undefined, set fruit equal to 'strawberry'".

1

u/foxhail Jul 10 '15

I'd think this would be preferred way of doing it. Sure it's longer, but ternary operators are definitely more readable than just using ||.

3

u/MadFrand Jul 11 '15 edited Jul 11 '15

but ternary operators are definitely more readable than just using ||

Maybe if you're unfamiliar with it.

x = x || "y" is pretty much instantly recognizable as a default value initialization.

1

u/foxhail Jul 11 '15

Actually now that I'm thinking about it again, I do tend to use || when setting a property in an object, just because it's shorter. Otherwise, I do try to use ternary instead when assigning a value to a variable. I guess in the end it's mostly up to preference.

-2

u/Mr-Yellow Jul 10 '15 edited Jul 10 '15

Really any need to check the type?

fruit = (fruit)?fruit:'strawberry';

(Apart from if you need empty strings and zeros)

2

u/Disgruntled__Goat Jul 10 '15

Did you read the article?

-1

u/Mr-Yellow Jul 10 '15 edited Jul 11 '15

Right, read it, meh... I'm using undefined when specially concerned with '' or 0, often aiming to first check length or something else which will identify a valid var rather than it's invalidity. Often hasOwnProperty when working with objects. Trying to reduce use of undefined and keeping typeof for checking actual types rather than lack of them, aiming for a consistent code-style.

12

u/lecherous_hump Jul 10 '15

The argument is "it's not readable to me". That's not an argument, imho. The || operator exists in every language I can think of and behaves the same in all of them. There's no reason it would be less readable than any other standard operator.

13

u/WiglyWorm Jul 10 '15

Yeah, there's really no valid justification given other than "I personally don't find it intuitive, so lets add underscore.js to our project!".

1

u/danneu Jul 10 '15 edited Jul 10 '15

It's a common source of bugs in Python, Javascript, and PHP to write if (x) ... when you didn't actually want 0 or "" to go down the falsey path.

Though the moral of the story should be "be appropriately explicit" or "watch out for this common gotcha" rather than "never use ||".

1

u/lecherous_hump Jul 10 '15

I'm not sure how you mean- empty string and 0 are false in PHP and JavaScript.

1

u/danneu Jul 10 '15

I'm referring to type coercion. Things that coerce to true are generally called "truthy" values. And things that coerce to false are "falsey".

For example, in Javascript:

"" ? "Truthy" : "Falsey"   => "Falsey"
"Hi" ? "Truthy" : "Falsey" => "Truthy"
0 ? "Truthy" : "Falsey"    => "Falsey"
1 ? "Truthy" : "Falsey"    => "Truthy"

For PHP, you can read more here: http://php.net/manual/en/language.types.boolean.php

2

u/lecherous_hump Jul 10 '15

I know what it is, I just don't understand where you wee going with it.

1

u/danneu Jul 10 '15

In some languages, like Clojure, only false and nil are falsey, so if (x) has two cases to reason about for the false path.

In the languages I listed, there are 4+ cases to reason about when you see if (x). Like in PHP, there's false, 0, "", 0.0, {}, [], null, etc.

You suggested that the post author's argument is "it's not readable to me", but that's not the case. Type coercion introduces this common gotcha. Their argument is: be explicit about the actual falsey cases you want to handle.

They focused too hard on the || operator, but their point isn't that controversial once you give them a more charitable interpretation.

23

u/[deleted] Jul 10 '15

Wow, what a useless article.

19

u/ogurson Jul 10 '15

I prefer using

typeof fruit === "undefined"  

over

fruit === undefined

as latter will fail if variable is not declared. It isn't problem in case of function params, but I like to use the same solution in all cases if it's possible.

6

u/Squirrels_Gone_Wild Jul 10 '15

This is correct, undefined can also be redefined, which would ruin the second comparison.

var undefined = 'squirrel';

6

u/Robbsen Jul 10 '15

This does not work in newer versions of Chrome and Firefox anymore

-1

u/Squirrels_Gone_Wild Jul 10 '15 edited Jul 10 '15

Good to know.

3

u/Lystrodom Jul 10 '15

Or you mean IE9. It was defined in Ecma script 5 that you can't redefine undefine

5

u/Lystrodom Jul 10 '15

This hasn't been true in years. ECMA Script 5 (so, IE9 and above) changes the spec such that you cannot redefine undefined. So unless you're still programming for IE8, don't worry about it.

2

u/x-skeww Jul 11 '15

The global undefined, Infinity, and NaN properties are read-only since ES5.

3

u/Capaj Jul 10 '15

undefined can also be redefined

while true, you really should not allow such code in your codebase in the first place.

3

u/Squirrels_Gone_Wild Jul 10 '15

Correct, but 3rd party code or libraries could change a global variable such as undefined without you knowing. the typeof check is much safer.

2

u/devoidfury Jul 10 '15

If you want to guarantee the safety of undefined, just wrap your code in an IIFE like so:

(function(undefined) {
    // code goes here
})();

AFAIK, coffeescript does this by default to prevent this exact situation.

2

u/until0 Jul 10 '15

As does jQuery, as well as most other libraries which have heavy cross talk issues.

1

u/Kautiontape Jul 10 '15

Is this a hypothetical situation, or is there an actual reason this would be done? And does that actual reason have a better solution which makes it plausible but a horrible practice?

2

u/Squirrels_Gone_Wild Jul 10 '15

It is, hopefully, hypothetical. but if you're using plugins or 3rd party code, they could easily do it without you knowing. Always best to test against an immutable value rather than what boils down to a global variable.

2

u/SnailCrusher Jul 10 '15

The latter solution is faster however.. I'd give you a jsperf link if it wasn't down atm.

-1

u/patrys full-stack Jul 10 '15

There is no magic variable named undefined in JavaScript. The latter example depends on JS seeing a reference to a variable that is not defined in the current scope and thus implicitly creating a new uninitialised variable named undefined. There is nothing special about the name however as it would work the same if written as if (fruit === yourMom). It's an anti-pattern and should be avoided.

4

u/x-skeww Jul 11 '15
> window.hasOwnProperty('undefined')
true
> window.hasOwnProperty('NaN')
true
> window.hasOwnProperty('Infinity')
true

These global properties are read-only since ES5.

1

u/patrys full-stack Jul 11 '15

Now that's embarrassing, I've been working with JS for years and somehow missed the addition of these. It used to be possible to break lots of JS code by simply writing undefined = 42;. I stand corrected.

1

u/[deleted] Jul 10 '15
$ node
> var undefined = "foobar";
undefined
> undefined;
undefined

2

u/AlGoreBestGore Jul 10 '15
var current = newValue > max ? max : (newValue < 0 ? 0 : newValue);

Am I a rebel now?

2

u/dead-fish Jul 10 '15

This is such a basic concept in JS and it's used everywhere. It doesn't work in all cases so you don't use it in all cases.

Their example is actually a perfect example of when you might want to use the || operator. I highly doubt an empty string or something falsey would be a valid input for their eatFruit() function so using the default value makes sense.

2

u/can_i_have Jul 10 '15

First time I saw the OR operator, it didn't add a mental overhead for me, but I went "wow, we can do this?".

If the OR operator adds mental overhead to any developer, it would be a red flag for me :)

1

u/hahaNodeJS Jul 10 '15

https://www.youtube.com/watch?v=hjCHD41I7ok

Sometimes I find it useful to do this if, for example, I need to allow an empty string, but not 0 or undefined.

(myVar !== undefined && myVar) || "default"

It's all about understanding the language you're working with.

2

u/until0 Jul 10 '15

I think a ternary is easier to read and accomplishes the same thing.

typeof myVar === "undefined" ? myVar : "default";

1

u/hahaNodeJS Jul 10 '15

Yep. Just providing an example, anyway. There are lots of ways to do this.

1

u/nikrolls Chief Technology Officer Jul 11 '15

Your example is backwards -- any defined value will be replaced by 'default', and an undefined value will be allowed through.

1

u/until0 Jul 11 '15

It's not a bug, it's a feature.

1

u/iams3b rescript is fun Jul 10 '15

I mean, undefined, 0, null, NaN, false... that all means that there isn't a fruit defined, and we need a default one either way yeah? Saves a lot of breakage using ||

1

u/siamthailand Jul 11 '15

The writer of this article shouldn't really be programming IMO.

1

u/frambot Jul 12 '15

it isn’t obvious why the OR operator would be used to assign default values.

Bullshit. It has plenty of precedence.

0

u/[deleted] Jul 10 '15

[deleted]

1

u/dariusj18 Jul 10 '15

Convention or antipattern?

0

u/[deleted] Jul 10 '15

[deleted]

0

u/dariusj18 Jul 10 '15

I must disagree with your disagreement. Yes, calling it an antipattern is a hyperbole, but the article points out very simple and clear drawbacks for using the || operator shortcut for variable assignment.

0

u/[deleted] Jul 10 '15

[deleted]

3

u/whatsmydickdoinghere Jul 10 '15 edited Jul 11 '15

no dude you need underscore.js didn't you hear him