Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript default parameter with extra assignment

Tags:

javascript

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?

like image 337
aw04 Avatar asked Sep 26 '22 14:09

aw04


1 Answers

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.

like image 61
Pointy Avatar answered Sep 30 '22 07:09

Pointy