I’m trying to figure out why you might use the following code:
var myObject = myObject || {};
I’ve seen this used several times, but don’t understand why this would be necessary. Thanks for your responses.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
People call JavaScript’s binary or
||the defaulting operatoris the same as
The following code
is used because multiple files are going to set and use the namespace, and you don’t want to overwrite the namespace if it has already been created. That way, it doesn’t matter which file is included first.
Here’s another example of defaulting.
However, be careful of the following problem Why does IE nuke window.ABC variables?
That is if a namespace has been defined using
And another file sets
In IE, it will overwrite the value of window.AppSpace to the empty object if the two scripts are in different script tags because of variable hoisting and the fact that IE doesn’t realize that
window.aandvar aat the top level are all pointing at the same variable.