I need to check if a object "objCR" is present in the current scope or not. I tried using below code.
if(objCR == null)
alert("object is not defined");
Let me know where I am wrong.
I need to check if a object "objCR" is present in the current scope or not. I tried using below code.
if(objCR == null)
alert("object is not defined");
Let me know where I am wrong.
Share Improve this question asked Dec 8, 2010 at 12:07 Vaibhav JainVaibhav Jain 34.4k48 gold badges115 silver badges165 bronze badges5 Answers
Reset to default 11Use the typeof
operator:
if(typeof objCR == "undefined")
alert("objCR is not defined");
As mentioned by others, using a typeof
check will get you some of the way there:
if (typeof objCR == "undefined") {
alert("objCR is undefined");
}
However, this won't distinguish between objCR
existing and being undefined (as would be the case if it had been declared but not assigned to, e.g. using var objCR;
) and objCR
never having been declared anywhere in the scope chain, which I think is what you actually want. If you want to be sure that no objCR
variable has even been declared, you could use try/catch
as follows:
try {
objCR; // ReferenceError is thrown if objCR is undeclared
} catch (ex) {
alert("objCR has not been declared");
}
if (typeof objCR=="undefined"){
alert("objCR is undefined");
} else {
alert("objCR is defined");
};
(!objCR)
will return true if objCR
is a boolean equal to false
I would suggest the obvious:
if (objCR==undefined) ...
I always have this to be safe:
if(typeof objCR == "undefined" || objCR == null)
alert("object is not defined or null");