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.
Use the typeof operator:
if(typeof objCR == "undefined")
alert("objCR is not defined");
objCR could easily be declared within the current scope but still be undefined. For example, var objCR; would do that.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");
}
I would suggest the obvious:
if (objCR==undefined) ...
typeof, as javascript doesn't protect the undefined keyword - you can actually have code which sets undefined = 42(!) which would break your comparison(objCR==undefined) fails in IE6 at least if objCR is undefined. Use typeof to be safe.ReferenceError in all browsers if objCR has never been declared; second, a comparison with undefined using == will also return true if objCR is null; third, that a variable that has been declared but not assigned a value will be undefined, and fourth, that undefined is not a reserved word and its value can be altered.I always have this to be safe:
if(typeof objCR == "undefined" || objCR == null)
alert("object is not defined or null");
null is definitely different from undefined, so this as it stands is wrong.