-3

I am trying to learn some javascript by working my way through some existing code and I came across this variable definition which I have not seen in the past. After searching I could not find an explanation so figured I would post here.

var colorCollection = colorCollection || {};

Could someone shed some light on what this type of definition means and why one might use this.

Prasanth K C
  • 7,073
  • 5
  • 39
  • 62
  • perhaps this one? http://stackoverflow.com/questions/4576867/javascript-or-operator-with-a-undefinded-variable – Zach Lysobey Dec 23 '13 at 04:35
  • 1
    If `colorCollection` is falsy, `colorCollection` will default to `{}`. It's commonly used as a hack for optional function parameters in JavaScript. – Blender Dec 23 '13 at 04:35
  • possible duplicate of [JavaScript OR (||) variable assignment explanation](http://stackoverflow.com/questions/2100758/javascript-or-variable-assignment-explanation) or [In Javascript, what does it mean when there is a logical operator in a variable declaration?](http://stackoverflow.com/questions/3088098/in-javascript-what-does-it-mean-when-there-is-a-logical-operator-in-a-variable) – Phil Dec 23 '13 at 04:35

1 Answers1

1

This is assigning colorCollection to its own value if it already exists, otherwise it will assign it an empty object.

It works like this - in javascript, any variable is "truthy", meaning that you can say something like this:

if (colorCollection) {
 // some code 
}

If colorCollection has a value (ie. it isn't undefined, null, NaN, 0, "", or false), the if statement will be true, and the code in // some code will run. The || operator will return the first value if it's truthy, otherwise it will return the last value. That's why this works.

mpataki14
  • 208
  • 2
  • 8