I’ve just started out with Javascript and I’m coming across declarations of the following type quite often:
var var_name = window.var_name = window.var_name || {};
Can someone explain what is the significance of such a declaration?
I’ve just started out with Javascript and I’m coming across declarations of the following
Share
This expression:
…simply returns the value of
window.var_nameunless that value is falsy (false,0,'',undefined,null, orNaN), in which case it evaluates to an empty object ({}). This is used to provide a default value whenwindow.var_namedoes not exist.The resulting value is then assigned back to
window.var_name:Which is then assigned to a (possibly) new variable named
var_name:In the global scope
var_nameis equal towindow.var_name. Inside a function,var_namewill refer to a new local variable.