Don't use || to set default values in JavaScript
codereadability.com
codereadability.com
What world is this guy living in? It's like it's the first time he's seen this and just decided "I don't like it, let me write an article about that".
Anyone working in JS for more than a month will have seen this as common practice. It much neater (and less mental headspace IMHO) than an extra if block. Particularly if you have more than one optional variable.
The only practical consideration raised is the falsy types can trip you up but that is easily negated. I have strong negative feelings for people who impose their own personal believes based on nothing but their feelings.
So long you're OK with that, it seems like a clean solution. It's JavaScript. There's tons of dumb stuff a JS coder must learn. If he's confused by || then he's likely to be unable to work on any real JS.
Honestly, 0 sounds like a default value in most cases anyway.
You mean adding an if block to check for the zero and blank string?
fruit = fruit === "" ? "" : fruit || "strawberry";
Woohoo! Javascript rocks! Note that fruit = fruit == "" ? "" : fruit || "strawberry";
May or may not be bugged depending on your understanding of a bug and whether you're a marmite fan. fruit = fruit === "" && "" || fruit || "strawberrry";
It's flexible too.. though imo your ternary operation is more obvious. ;-)Personally, I find that once you understand JavaScript, the beauty in what you can do, especially for input validation (which is an ugly, ugly thing) works so well in this language.
The way he wants to solve it however uglier imho
foo = bar || baz is perfect when parsing inputs where unset is passed as "" or 0. To no great surprise, HTML forms are one such beast.
The Boolean operators are simply a shorthand for if (!foo) foo = bar -- when you mean if (foo === undefined) foo = bar; then simply write that instead. At least omit the unnecessary braces and white space.
Verbose code is not necessarily more readable. You may be able to code your way around a reader not comprehending JS rules regarding Boolean coercion, but those rules are based on real world inputs which often do not have a special 'undefined' value.
0 always trips people up in this, or other means of coercion. Other than that one case, I find the shortcut of || to be pretty much invaluable.
This is an example of something you should just learn how it works, rather then assume it's stupid or wrong because you don't know how the environment works. You should have seen how many people went up in arms at LINQ and even Lambda functions in C#. I've seen similar comments about lambda/fat-arrow functions coming into JS.
Like "what are the falsy values in JavaScript" (I usually let people get away with 3+ of them)
In the browser a very primary purpose for JavaScript is input validation... this includes strings... being able to reuse a method for internal validation is useful as well. Knowing how to do something useful in a language is a perfectly fine interview question.
It isn't like I'm asking people to write a bubble-sort, or how an IEEE 754 number is structured and how that relates to JS... Or how to determine the number of marbles in a given jar... or any other of other questions I've been asked in an interview. I'm asking someone to validate a simple input in one of the most widely used programming languages on the planet.
Sorry to go on a rant.. but hiring is hard, and when you are looking at someone why says they have a lot of experience with the skills that you are looking for (full-stack javascript/node)... expectations shouldn't be too low.
I'm more than happy to talk to people with other backgrounds and skills... I've hired plenty of newer/eager learners who don't have a lot of experience, but demonstrated the ability to work through a problem. In my mind effort/ambition/trying-stuff means more than specific experience.
var undefined = "raspberry";
function eatFruit (fruit) {
if (fruit === undefined) {
fruit = "strawberry";
}
...
}
eatFruit("raspberry");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.
I'm sure this used to work, a few years ago... but I may be getting old.
$ node
> var bar = undefined = "foo";
undefined
> bar
'foo'
> undefined
undefined
> if (foo === void 0) ...
//or
var undef;
...
if (foo === undef) ... if (typeof fruit === "undefined") {
fruit = "strawberry";
}
Unless your doing something like: (function(undefined) {
})();If the binding exists at all, you can just check for its value. And parameters always create a binding pretty much by definition.
So no, there is no reason to use `typeof` to check whether a parameter is `undefined`.
If you fear that somebody rebound the global `undefined` for some insane reason, you can use `void 0` instead.
In the example with the undefined check... what if undefined is a valid argument? You should actually check the length of the arguments object.
See, you can always find examples of when you shouldn't do something. That doesn't mean you shouldn't EVER do it. At the end of the day, people who read and write code need to understand how it works. You can only protect people from themselves so much.
When C come out, it did not include a bool type, since it could be easily implemented as integer or char. The result was, that every bigger project had its own standard of the boolean type. This lead to the situation that bringing together different libraries or projects in the same company, you very soon had four or more different (and potential incompatible) boolean types with different constants for TRUE, FALSE, true, false and UNDEFINED. The programmers where happy to deal with those ...
It would be best (and fastest) to include something like default parameters into the language much sooner ...
But at least in this case, I see much less trouble as with the C type and I do not agree with the author that there is mental overhead involved with the OR operator, since you normally get used to it fast.
The first part of the argumentation is indeed based on the author's feelings. The second part I don't think is an issue for most real world use-cases (Objects, Strings and, to a lesser extent, Numbers).
On the underscore (_.defaults) recommendation: let's set our goals straight [1]. Aim for a good level of JavaScript understanding. Instead of library knowledge to make up for the lack of the former.
There are many valid cases where the incoming parameter could be either undefined or null.
Really?! This is common knowledge for anyone writing JS for more than a week. It's used EVERYWHERE.
falsy values are: "", 0, null, undefined, NaN and false
Everything else is truthy.
I kind of wish that Invalid Date (invalidDt.valueOf() === NaN), empty arrays, and objects without any properties were also falsy sometimes. Though I also wish that sometimes 0 was easier to separate from other falsy values.
article = skill || 'troll'
http://stackoverflow.com/questions/27509/detecting-an-undefi...
Aparently the issue is more complicated than I thought, because the following comparison is used:
obj[key] === void 0
Are they really defending themselves against the function being rebound with undefined shadowed?
http://adripofjavascript.com/blog/drips/javascripts-void-ope...
You mean replace perfectly valid javascript with a complicated nodejs pipeline in order to make scripts run in the browser now? hell no.
Not to mention being able to break code into discrete modules that can be utilized without having to jump through namespace hoops or global collisions (does $ mean jQuery, Prototype, document.querySelectorAll, ...).
Huh? Babel plugs into whatever build pipeline you already have be it webpack, gulp, etc... You also get the benefits of being able to use ES6 today which has tons of great features.
I feel this is an excellent trade-off for any non-trivial project.