Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a variable is loaded in JavaScript?

How do I see if a certain object has been loaded, and if not, how can it be loaded, like the following?

if (!isObjectLoaded(someVar)) {
    someVar= loadObject();
}
like image 636
SeanDowney Avatar asked Sep 18 '08 19:09

SeanDowney


2 Answers

If it is an object then you should just be able to check to see if it is null or undefined and then load it if it is.

if (myObject === null || myObject === undefined) {
   myObject = loadObject();
}

Using the typeof function is also an option as it returns the type of the object provided. However, it will return null or undefined if the object has not been loaded so it might boil down a bit to personal preference in regards to readability.

like image 199
rjzii Avatar answered Mar 08 '23 12:03

rjzii


if(typeof(o) != 'object') o = loadObject();
like image 26
Tom Ritter Avatar answered Mar 08 '23 12:03

Tom Ritter