I have found a code in javascript which is creating an object. But I have clearly no idea what exactly the below code does.
var a = a || {};
An explanation would be appreciated.
I have found a code in javascript which is creating an object. But I have clearly no idea what exactly the below code does.
var a = a || {};
An explanation would be appreciated.
The first step here is to understand that it really becomes this:
var a;
a = a || {};
...and that var a
is a no-op if the a
variable has already been declared previously in the current scope.
So the first part (var a
) makes sure a
exists as a variable if it doesn't already.
The second part then says: If a
has a "truthy" value, keep it (don't change it). If it has a "falsey" value, assign {}
to a
.
The "falsey" values are 0
, NaN
, null
, undefined
, ""
, and of course, false
. Truthy values are all others.
This works because of JavaScript's curiously-powerful ||
(logical OR) operator which, unlike some other languages, does not always result in true
or false
; instead, it evaluates the left-hand operand and, if that's truthy, takes that value as its result; otherwise, it evaluates the right-hand operand and uses that as its result.
Look at the double-pipe like a logical OR.
var a = a OR { };
which pretty much means, if a
has a Javascript truthy value, (re) assign a
to a
, otherwise assign a new object reference.
It sets as the value of the variable a
either:
a copy of the current value of a
if a
exists and is a primitive type
a reference to the current value of a
if a
exists and is a complex type
a new object if a
does not exist
Its like ordinary if condition(seems ternary operator) checking boolean and assigning values