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.
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.
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
}
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).