-2

I'm new to javascript from C++ background. I always see code like

var variableName = variableName || {};

It seems quite strange to me. Can somebody explain the meaning of the code? Thanks a lot.

Ming Li
  • 11
  • 1
  • You're asking about how [logical operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Logical_operators) work. – hon2a Dec 07 '14 at 10:56
  • **exact** duplicate of [What does “var FOO = FOO || {}” mean in Javascript?](http://stackoverflow.com/questions/6439579/what-does-var-foo-foo-mean-in-javascript) – Qantas 94 Heavy Dec 07 '14 at 11:04

2 Answers2

3

It means if that variable isn't set, make it to be a new empty object and if it is set, use the value of that variable. It equals to code:

var variableName;
if(!variableName){
    variableName = {};
}

var a = a || {}; // {}
var b = {"key":"value"};
var b = b || {}; // {"key":"value"}

Normally it's used to create a namespace to organize the code. For example,

var myNameSpace = myNameSpace || {};
myNameSpace.print= function(msg) {
    console.log("message is: "+msg);
}
myNameSpace.bar = function(){
    //do some thing
}
user2466202
  • 1,007
  • 9
  • 7
2

That means, that if variableName is set, variableName should stay that value. Else, if it's not set, it should become an object (in this case an empty one).

baao
  • 62,535
  • 14
  • 113
  • 168