I was wondering for a longer time what the below means:
var a = a || { b : 1 }
if 'a' had any properties assigned before... they dissapear. So what is a purpose of the above syntax ?
I was wondering for a longer time what the below means:
var a = a || { b : 1 }
if 'a' had any properties assigned before... they dissapear. So what is a purpose of the above syntax ?
I love this kind of syntax. In my opinion, it is very elegant.
The explanation is fairly simple. What you have here is a conditional expression using the ||
(or) operator. This will assign a value to the variable according to the result of the conditional.
In this case, the condition is a || { b : 1 }
, so if the variable a
has already been defined (i.e. not equal to a false value), then the variable a
will be left unchanged. However if a
has not been defined yet, then it will be assigned the value of the object literal { b : 1 }
.
This method of syntax is usually used to define default values.
For example:
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 argument name
has not been passed to the function, the default name Dude
will be used.
if a
is falsy ie (false, 0, undefined, null, "", NaN) assign the default value { b : 1 }
to it
The code assigns the object { b: 1 }
to a
if a
is undefined.
a || { b: 1 }
means a
or { b: 1 }
and the ||
operator returns the first operand which is true. So if a
defined it will returned a
otherwise it will return { b: 1 }
(since that is true).
If a
has some value already assigned then it will take that values else it will assign object {b:1}
to a
.