What is the purpose of the 'var a = a || {b: 1}' syntax

I was more wondering what is below:

var a = a || { b : 1 } 

if 'a' had any properties assigned earlier ... they disappear. So what is the purpose of the above syntax?

0
source share
4 answers

I like that syntax. In my opinion, it is very elegant.

The explanation is quite simple. You have a conditional expression here using the || (or). This will assign the value to the variable according to the result of the conditional expression.

In this case, the condition a || { b : 1 } a || { b : 1 } , therefore, if the variable a already defined (that is, it is not equal to a false value), then the variable a will remain unchanged. However, if a is not yet defined, then it will be assigned the object literal value of { b : 1 } .

This syntax method is commonly used to determine default values.

For instance:

 function say_hello( name ){ var the_name = name || 'Dude'; alert( "Hello, " + the_name ); } say_hello( "Lix" ); // OUTPUTS: Hello, Lix say_hello(); // OUTPUTS: Hello, Dude 

If the name argument was not passed to the function, the default name is Dude .

+6
source

if a falsy , i.e. (false, 0, undefined, null, "", NaN) assign a default value of { b : 1 } to it

+3
source

The code assigns the object { b: 1 } a if a is undefined.

a || { b: 1 } a || { b: 1 } means a or { b: 1 } , and the operator || returns the first operand that is true. Therefore, if a defined, it will return a , otherwise it will return { b: 1 } (since this is true).

+1
source

If a already assigned some value, then it will take these values ​​differently, it will assign the object {b:1} to a .

0
source

All Articles