0

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.

chridam
  • 100,957
  • 23
  • 236
  • 235

5 Answers5

2

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

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.

jAndy
  • 231,737
  • 57
  • 305
  • 359
0

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

Mitya
  • 33,629
  • 9
  • 60
  • 107
0

if a is undefined or false set a = {}

Linora
  • 10,418
  • 9
  • 38
  • 49
0

Its like ordinary if condition(seems ternary operator) checking boolean and assigning values

albert Jegani
  • 462
  • 5
  • 15