最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Check if a variable is in the scope or not in Javascript - Stack Overflow

programmeradmin9浏览0评论

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 badges
Add a comment  | 

5 Answers 5

Reset to default 11

Use 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");
发布评论

评论列表(0)

  1. 暂无评论