1

I met some syntax, which is not clear for me, like this:

anotherVariable = anotherVariable || {};
var variable = anotherVariable.member = anotherVariable.member || {};

What does the code above mean?

Erik Kianu
  • 89
  • 9

4 Answers4

1

This is default value setter.

anotherVariable = anotherVariable || {};

if anotherVariable is falsy then it'll set {} in anotherVariable.

'' , null, 0 ,undefined,NaN consider falsy in javascript.

This is same for

var variable = anotherVariable.member = anotherVariable.member || {};

if anotherVariable.member is falsy then {} will be set in anotherVariable.member and then anotherVariable.member will be set in variable.

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
1

Here's a combination of few things

  1. Any not null object in js is true in all comparisons
  2. {} is a definition of empty object
  3. So it means this:

    if (anotherVariable != null) { anotherVariable = {}; }

suvroc
  • 3,058
  • 1
  • 15
  • 29
0

anotherVariable become an empty hash/opbject {} if it is undefined

leguano
  • 171
  • 1
  • 6
0

It is pretty simple :

var a = b || {};

set variable "a" to "b". If b is null or undefined, set "a" to {}

var variable = anotherVariable.member = anotherVariable.member || {};

set anotherVariable.member to {} if it's null or undefined. then set variable to anotherVariable.member

Apolo
  • 3,844
  • 1
  • 21
  • 51