I have a questions regarding variable scope in Javascript. I have a series of scripts on a webpages loading at different times. I need a global object called MyVar for example to be accessible to them all. I want to avoid redefining it but I guess it has to be defined at some point by the first script. My question is is using var MyVar = MyVar || {} a solution?
Thanks
/**
* Script 1
*/
var MyVar = MyVar || {};
MyVar.config = {
x : 2,
y : 3
};
/**
* Script 2
*/
//is this correct?
var MyVar = MyVar || {};
//to which MyVar am I assigning the apple property?
MyVar.apple = 'red';
UPDATE
Great answers so far guys thanks.
One last part though, what is the second var statement doing when I repeat var MyVar = MyVar || {}; for the second time? Is it creating a new var in the global scope called MyVar that is assigned the value of the existing MyVar ?
Other posters are right to assume I have these scripts loading synchronously in <script> tags however due to division of labour I create the scripts then don’t control when and how they are loaded so need a fool-proof method to create / utilize my MyVar object.
Thanks
Is any of them loaded asynchronously? If it’s just a series of
<script>tags, they will be loaded synchronously, in sequence.If you declare
MyVaron the global scope every time, there will be only oneMyVar. Theappleproperty will be created on the existing variable, if it exists, or in the empty object created withvar MyVar = MyVar || {};if it doesn’t.Bottom line: after the first
var MyVar = MyVar || {};, following declarations will be ignored, and new properties will be appended to the existing variable. Just be careful not to overwrite existing properties.