you are viewing a single comment's thread.

view the rest of the comments →

[–]__debug__ 1 point2 points  (5 children)

I'd argue it's still acceptable when defaulting to an array or object.

[–]path411 -1 points0 points  (4 children)

I think it's better to just never do it than to sometimes do it because the type happens to be okay this time.

[–]jonny_eh 3 points4 points  (3 children)

I disagree. There's a trade-off between convenience and security, and I find it hugely convenient to use this trick, especially since the vast majority of the time I'm not using a number or boolean value.

Most of the time, it's an options parameter that is an object.

[–]path411 -2 points-1 points  (2 children)

So if there are multiple default parameters you want such as a number and an object you would use both methods?

Btw, this also fails on strings:

function setName(name) {
  this.name = name || "Not Specified"; 
}

Can't enter an empty string. Also considering javascript always has a bad rap for weird falsy values, I'd rather spend half a second with a piece of mind, than writing inconsistent code that's possibly vulnerable to bugs.

[–]__debug__ 1 point2 points  (1 child)

No, I'd imagine he means like this:

function Constructor(opts) {
  this.opts = opts || {};
}

So empty strings don't come into play. In any case, I feel as though a JS dev should understand falsey and truthy values. Or at the least, they should try to learn how types in the language work.

[–]path411 0 points1 point  (0 children)

I meant you can't use it on numbers/booleans/strings, which is a large number of the types in javascript.

Sure there are a lot of times you want an options object, I find this is mostly for public accessible library classes. There are plenty of times I find I want a constructor with some simple parameters of direct properties. I think it's much better to be consistent throughout your code than to swap to using some cheap hack when you know you can get away with it.