0

I know that || means OR that's easy. But recently I saw this piece of code :

var myArray = [['activity', 'none'] , 
               ['movies', 'activity'],
               ['theater','activity'],
               ['drama', 'movies'],
               ['comedy', 'movies'],    
               ['puppet', 'theater'], 
               ];

var nodes = {};
for (var i in myArray) {
    var child = myArray[i][0];
    var parent = myArray[i][1];
    var children = nodes[parent] || []; // what is this ? 
    children.push(child);
    nodes[parent] = children;
}

alert(nodes);

I am confused. children looks like it is an array because it has a .push method. But var children = nodes[parent] || []; points to : children is boolean . .

Also, how can one compare an object and an empty array ? var children = nodes[parent] || [];

Thanks

Alex
  • 355
  • 7
  • 25
  • 1
    It's [logical `OR`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR_%28.7C.7C%29) there ; ). – Teemu Jan 20 '15 at 18:02
  • 2
    you can use `||` to set a default value; in this case, an empty array (`[]`) is the default value for `children` if `nodes[parent]` is falsy. – Don Jan 20 '15 at 18:03
  • 1
    See http://stackoverflow.com/questions/1011317/replace-a-value-if-null-or-undefined-in-javascript – Pete Jan 20 '15 at 18:05
  • If you feel that your specific confusion with this issue is not addressed by the duplicate I've used, please let me know. – apsillers Jan 20 '15 at 18:06

1 Answers1

3

If the nodes[parent] is empty or null an empty array is assigned to children variable (for not beeing null).

Knut Holm
  • 3,988
  • 4
  • 32
  • 54