Check if a variable is in scope or not in Javascript

I need to check if the object "objCR" is present in the current area or not. I tried using the code below.

if(objCR == null)
alert("object is not defined");

Let me know where I am wrong.

+3
source share
5 answers

Use the operator typeof:

if(typeof objCR == "undefined")
   alert("objCR is not defined");
+7
source

As others have already mentioned, using verification typeofyou will get part of the path:

if (typeof objCR == "undefined") {
    alert("objCR is undefined");
}

objCR undefined ( , , , , var objCR;) objCR - , , , . , objCR , try/catch :

try {
    objCR; // ReferenceError is thrown if objCR is undeclared
} catch (ex) {
    alert("objCR has not been declared");
}
+2
if (typeof objCR=="undefined"){
    alert("objCR is undefined");
} else {
    alert("objCR is defined");
};

(!objCR)will return true if objCRis a boolean equal tofalse

+1
source

I would suggest the obvious:

if (objCR==undefined) ...
0
source

I always have this to be safe:

if(typeof objCR == "undefined" || objCR == null)
   alert("object is not defined or null");
0
source

Source: https://habr.com/ru/post/1779166/


All Articles