Not sure how to ask this, but what are they trying here?

In JS, what do they say on the next line?

members = members || {};

      

I am confused by the OR operator. Is it said if it, if the members are not zero, makes it equal to the members, or creates a new object?

+3


source to share


5 answers


It says if members

is something that is not undefined

or "falsey" then it will set it to members

, otherwise it will set it to a new empty JavaScript object.

This type of code is often used if the code is run more than once. The first time through members

will usually be undefined

, but in subsequent times it will have a meaning that you would not want to lose.



Things to watch out for with these types of statements: Some real values ​​such as 0

or false

will be evaluated as "false". In this case, this is not a problem. In the future, if you use something like this, keep this in mind. Any "false" will default to the "other side" of the operator ||

. In this case {}

.

+2


source


members = members || {};

      

This means that if the member variable is not undefined then members == members

elsemembers == {}



This case is used when members return an object ({}) then use members

, and if members do not return an object, use{}

+2


source


It uses Javascripts for values ​​|| an operator that "returns the first thing that is true"

So in this case it will return members if members exist, otherwise it will return {}.

This is a quick way to set things up if they haven't already been set (e.g. to implement default arguments for functions)

+2


source


They say that if the members of a variable do not exist, declare it as an empty object.

if it exists use it

Revision: As pointed out, members should be "false" as reset for an empty object. Be careful if there is a chance when using this method that members might be set to 0, an empty string, etc.

0


source


This basically means that if the members already exist use that, otherwise create a new object.

0


source







All Articles