In javascript, we often see code like the following to set a default parameter when we don't care to ignore falsey values.
function SomeObject (param) {
this.param = param || {};
}
Occasionally though, when reading code, I'll come across the following variation:
function SomeObject (param) {
this.param = param = param || {};
}
Can someone explain to me the use case for this?
In this code:
function SomeObject (param) {
this.param = param = param || {};
}
two separate assignments are made: one to the param
local variable (the actual argument to the function) and one to a property of this
, whatever that happens to be. Those two different assignment targets are not the same. (They'll get the same value of course, but they're two separate places to put values.)
In my experience, it's far more common to see a simple default established for the parameter itself:
function whatever(x) {
x = x || {};
There's nothing wrong, however, with assigning to an object property when that makes sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With