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
  • 95,056
  • 21
  • 214
  • 219

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
  • 959,406
  • 173
  • 1,780
  • 1,769
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
  • 223,102
  • 54
  • 301
  • 354
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
  • 32,084
  • 8
  • 49
  • 92
0

if a is undefined or false set a = {}

Linora
  • 9,673
  • 9
  • 37
  • 47
0

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

albert Jegani
  • 424
  • 5
  • 15