Javascript Default Option with Additional Purpose

In javascript, we often see code like the one below to set a default option when we don't want to ignore false values.

function SomeObject (param) { this.param = param || {}; } 

Sometimes, though, while reading the code, I came across the following option:

 function SomeObject (param) { this.param = param = param || {}; } 

Can someone explain me a usage example?

+5
source share
1 answer

In this code:

 function SomeObject (param) { this.param = param = param || {}; } 

Two separate assignments are performed: one for the local variable param (the actual argument of the function), and the other for the this property, no matter what happens. These two different destination goals are not the same. (Of course, they will get the same value, but they are two separate places to place the values.)

In my experience, it’s much more common to have a simple default set for the parameter itself:

 function whatever(x) { x = x || {}; 

However, there is nothing wrong with assigning to an object, if that makes sense.

+4
source

Source: https://habr.com/ru/post/1232624/


All Articles