如何确定变量是'undefined'还是'null'?

How do I determine if variable is undefined or null? My code is as follows:

var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
  //DO SOMETHING
};
<div id="esd-names">
  <div id="name"></div>
</div>

But if I do this, the JavaScript interpreter halts execution.

转载于:https://stackoverflow.com/questions/2647867/how-to-determine-if-variable-is-undefined-or-null

weixin_41568208
北城已荒凉 only the <> diamond moderator can manually lock and unlock the stackoverflow post: meta.stackexchange.com/questions/22228/… :)
大约 3 年之前 回复
csdnceshi63
elliott.david Can we nominate this question to be locked? I don't have enough rep. @tats_innit
大约 3 年之前 回复

25个回答

You can use the qualities of the abstract equality operator to do this:

if (variable == null){
    // your code here.
}

Because null == undefined is true, the above code will catch both null and undefined.

csdnceshi57
perhaps? I'm trying to test if event is null in firefox and an error blocks the execution: "event is undefined"
大约 2 年之前 回复
if (variable == null) {
    // Do stuff, will only match null or undefined, this won't match false
}
csdnceshi72
谁还没个明天 answer is not working for undifined variable lol
大约 5 年之前 回复
csdnceshi62
csdnceshi62 This answer is WRONG. An undefined variable produces ReferenceError.
大约 6 年之前 回复
csdnceshi61
derek5. The fact that code makes sense to you doesn't make it sensible code.
6 年多之前 回复
csdnceshi58
Didn"t forge can you point me to a reference that explicitly states that == is broken. The coercive if(variable == null) in this answer makes complete sense to me...
6 年多之前 回复
csdnceshi61
derek5. Let's emphasize that this answer takes advantage of the broken nature of == and is therefore unwise....it would be better to SPECIFY if (variable === null || variable === undefined)....that way someone reading the code knows exactly what it's meant to do and when.
接近 7 年之前 回复
csdnceshi55
~Onlooker as user216441 pointed out this is a nogo for undeclared variables jsfiddle.net/U2VHs/3
大约 7 年之前 回复
csdnceshi66
必承其重 | 欲带皇冠 Just figured out you can add this comment: /*jshint eqnull:true */ to the top of your JS document or function, and JSHint will stop warning you about your uses of == null.
7 年多之前 回复
csdnceshi66
必承其重 | 欲带皇冠 For some reason JSHint doesn't like this. :(
7 年多之前 回复
csdnceshi71
Memor.の It only works for declared variables, not variables that may or may not be declared, which is rarely the case. (You need to use typeof + a null check for that case)
8 年多之前 回复
csdnceshi75
衫裤跑路 Failed to me in chrome console... ReferenceError: variable is not defined, so it might work, but not for me...
8 年多之前 回复
weixin_41568110
七度&光 Just in case anybody thinks this is another half-answer, this actually does work. undefined evaluates equal to null.
10 年多之前 回复

Combining the above answers, it seems the most complete answer would be:

if( typeof variable === 'undefined' || variable === null ){
    // Do stuff
}

This should work for any variable that is either undeclared or declared and explicitly set to null or undefined. The boolean expression should evaluate to false for any declared variable that has an actual non-null value.

weixin_41568208
北城已荒凉 No. The first conditional can be false, and the second conditional can be true. Consider the case when variable is defined and has the value null.
4 年多之前 回复
csdnceshi53
Lotus@ Correct me if I am wrong, but isn't the first conditional a superset of the second one, and therefore the second conditional is superfluous?
4 年多之前 回复
weixin_41568174
from.. This is a better solution because as @Rogue pointed out, the variable might not be declared.
4 年多之前 回复
csdnceshi79
python小菜 that will cause a ReferenceError if the variable isn't declared. If you don't know whether or not a variable is declared, used the above solution. If you can guarantee that the variable is at least declared, you can use variable == null
5 年多之前 回复
csdnceshi55
~Onlooker what about directly checking if(variable===undefined) instead of using typeof?
5 年多之前 回复
csdnceshi68
local-host I recognize that typeof is an operator, not a function, so it doesn't need the parentheses, but I appreciate the parentheses nonetheless - simply for reading clarity.
大约 6 年之前 回复

The standard way to catch null and undefined simultaneously is this:

if (variable == null) {
     // do something 
}

--which is 100% equivalent to the more explicit but less concise:

if (variable === undefined || variable === null) {
     // do something 
}

When writing professional JS, it's taken for granted that type equality and the behavior of == vs === is understood. Therefore we use == and only compare to null.


Edit again

The comments suggesting the use of typeof are simply wrong. Yes, my solution above will cause a ReferenceError if the variable doesn't exist. This is a good thing. This ReferenceError is desirable: it will help you find your mistakes and fix them before you ship your code, just like compiler errors would in other languages.

You should not have any references to undeclared variables in your code.

csdnceshi62
csdnceshi62 ....what does that mean
2 年多之前 回复
csdnceshi59
ℙℕℤℝ its better to put undefine in single qoutes, 'undefined' because it will make it more understandable..
2 年多之前 回复
csdnceshi62
csdnceshi62 if (variable) tests truthiness. It would count out false, 0, NaN, and an empty string as well as null and undefined, so it is not the correct answer here. As for instanceof, if the questions is "IS THIS VARIABLE NULL OR UNDEFINED?" (perhaps you want the value to be null or undefined...) you cannot ascertain that with instanceof, except by checking that the value isn't an instance of any other type, which is crazy. So that is also the wrong answer here.
大约 3 年之前 回复
csdnceshi50
三生石@ Can't you just do if (variable) in Javascript? Also, maybe people mean to reference instanceof instead of typeof -- that is a best practice according to Nicholas Zakas.
大约 3 年之前 回复
csdnceshi62
csdnceshi62 That conditional would evaluate to true in all cases where the variable is neither null nor undefined, so if that's what you want then yes, it will gives the desired result. You could test that out pretty easily btw :)
3 年多之前 回复
csdnceshi73
喵-见缝插针 can I use it as - if (variable != null) {} ? will it give the desired result ?
3 年多之前 回复
csdnceshi62
csdnceshi62 And determining that does not require typeof. The answers here can distinguish between undefined and "not received at all," which is certainly impossible with typeof. And to distinguish between the other 8 items you listed, only === would get the job done. I can't even begin to imagine how you arrived at the conclusion that typeof will distinguish between 0 and 1 or true and false but === won't.
3 年多之前 回复
csdnceshi55
~Onlooker You say "You should not have any references to undeclared variables in your code" but you forget you need to parse service calls which might, or might not declare properties. Someone needs to know if someRemoteObjectReceived.randomProperty is not received at all, null, undefined, true, "true", "false", false, 1 or 0 depending of a series of uncontrollable events.
3 年多之前 回复
weixin_41568184
叼花硬汉 which is just to say, its a common thing for languages with a low cost of entry like javascript and php vs one where you need a more intricate understanding of how a language works before you can really program in it, such as, say, Haskell or Scala
3 年多之前 回复
weixin_41568184
叼花硬汉 word, lol with a language like JS with 8 gazillion people of all coding levels and backgrounds trying to program it I doubt there will be an end to comments supporting bad practice or outright faulty understanding of a concept like an undeclared variable, which would throw a compiler error in other popular statically typed languages but is capable of just being "smoothed over" in a dynamic language like JS
3 年多之前 回复
csdnceshi62
csdnceshi62 I gave up on arguing with the people who still comment on this. Once a year or so I ask a mod to clean up comments. There have been so, so many people trying to convince me this is wrong. It never ends.
3 年多之前 回复
weixin_41568184
叼花硬汉 optional parameters may be undefined if they are optionally not provided, but they are most definitely declared variables. They are declared and have a value of undefined, as any declared but uninitialized variable would, ie var someVar; so your argument doesn't really hold up
3 年多之前 回复
csdnceshi54
hurriedly% -OP: The statement about those comparisons being "100% equivalent" is SIMPLY WRONG, as you noted in your own EDIT, the second will cause a ReferenceError. As for the assertion: "You should not have any references to undeclared variables in your code." REALLY? Ever heard of Optional Parameters? jsfiddle.net/3xnbxfsu
接近 4 年之前 回复
weixin_41568126
乱世@小熊 One entirely legitimate use case is in Microsoft Dynamics CRM, where the execution of custom scripts is triggered through front end (UI) configuration and variables are passed (or not passed) from a string that is again defined in an input box in the front end.
接近 4 年之前 回复
csdnceshi72
谁还没个明天 Typically, such "possibly declared variables" are globals, i.e. properties of the window object, and the standard solution is to refer to them explicitly as such, e.g. if (! window.load_module_1) return;.
接近 4 年之前 回复
csdnceshi68
local-host imagine i want to check if load_module_1==1 but the load_module_1 can be undefined because depends on loading ajax. How can in check for its value==1 and does not get the undefined error? in a single line of if(!x){return;}
接近 4 年之前 回复
csdnceshi62
csdnceshi62 Yes because you wrote !== instead of !=.
大约 4 年之前 回复
csdnceshi75
衫裤跑路 if (variable !== null) still goes in even though it's undefined...
大约 4 年之前 回复
csdnceshi62
csdnceshi62 You don't need typeof to check data['token'] -- that can be done by if (data.token != null) { /* use data.token */ } . It's not different. You are, however, right about Angular. They have some very specialized methods in there, like isBlankObject and hasCustomToString. Evidently they wanted to cover both the case where the variable was undefined/null as well as undeclared references. While you're correct about their code, for most people this is not what they are looking for, and I stand by my assertion that if you think you need it, you're probably mistaken.
4 年多之前 回复
weixin_41568110
七度&光 You forgot many use cases. What about data you get from somewhere else such as url query params or json data from some API? What about dynamic structure? You should be able to test if data['token'] is defined? By the way, you mentioned Angular Framework but why would Angular define some angular.isDefined function if it was useless? Your answer is a bit super strict and lack of pragmatism.
4 年多之前 回复
csdnceshi62
csdnceshi62 That's more of a stylistic point. If the variable hasn't been declared at all, that's really just bad writing on the part of the author. You should know whether your variable has been declared or not, that shouldn't be a question. But yes, if for some reason that's the case, this should be changed to window.variable instead of just variable, which will not cause a reference error. Typeof should be avoided.
6 年多之前 回复
csdnceshi61
derek5. This will cause a ReferenceError and break execution if variable is not defined or referred to at all in the code, using typeof is safer.
6 年多之前 回复

jQuery attr() function returns either a blank string or the actual value (and never null or undefined). The only time it returns undefined is when your selector didn't return any element.

So you may want to test against a blank string. Alternatively, since blank strings, null and undefined are false-y, you can just do this:

if (!EmpName) { //do something }
csdnceshi70
笑故挽风 I realise this is a cold question, but jQuery will return undefined if the attribute doesn't exist on the element (not just just if the selector has no matching elements, as per the answer). For example, an img with no src would return undefined for $('img').attr('src');
大约 2 年之前 回复
csdnceshi75
衫裤跑路 I know this is late, but it will hopefully help people who come here later. The reason you get an error is because it has not been declared at all. Usually you'd have EmpName(or some other variable) be passed into a function, or the return value of another function and therefore declared(Example: "var x;"). To test if it returned undefined, or null, or blank string, you can use the above solution.
7 年多之前 回复
csdnceshi76
斗士狗 Chrome 17.0.963.78 m gives this error: ReferenceError: EmpName is not defined
8 年多之前 回复

jQuery check element not null

var dvElement = $('#dvElement');

if (dvElement.length  > 0) {
    //do something
}
else{
    //else do something else
}
if (typeof EmpName != 'undefined' && EmpName) {

will evaluate to true if value is not:

  • null

  • undefined

  • NaN

  • empty string ("")

  • 0

  • false

csdnceshi75
衫裤跑路 I do believe if(variable === undefined) without the quotes works best for catching any undefined object or primitive before sending it on to other instructions that might crash with it.
大约 2 年之前 回复
csdnceshi65
larry*wei I think you've misread what I wrote. I agree that leaving out the typeof check will cause a ReferenceError if the variable is not declared. The typeof check just means that instead of a compile-time error, the expression will simply evaluate to false. This isn't what OP should want - he should want to fix the undeclared variable. So instead of an error which will immediately be found by a developer, you'll get a potentially much more subtle bug which may take some time to debug and may get into production unnoticed. So in this case it's better to let it throw the exception.
2 年多之前 回复
csdnceshi51
旧行李 that will ReferenceError and break execution if the variable is not defined or referred to at all in the code, using typeof is safer. If its saas then no problem, If its like self hosted application. Fixing a bug is mess.
2 年多之前 回复
csdnceshi65
larry*wei As Aerovistae wrote under "Edit again", you shouldn't be using undefined variables, and throwing an error in this case is good because you'll notice the mistake quickly and fix it.
2 年多之前 回复
csdnceshi78
程序go I think Rudy might have meant this var EmpName; if (EmpName). Where the variable is defined but not assigned a value.
接近 4 年之前 回复
csdnceshi51
旧行李 If variable is not defined. then if(EmpName) will throw error
接近 4 年之前 回复
csdnceshi77
狐狸.fox This is the same as if (EmpName). If it's undefined will be falsy already.
接近 4 年之前 回复
csdnceshi80
胖鸭 Please provide a reference of this javascript especification
4 年多之前 回复
csdnceshi50
三生石@ I think this is a dangerous technique that has spread like wild fire. Because a lot of the variables that are checked could be boolean or numbers. So if the user does not fully understand the consequences, this is no good.
接近 5 年之前 回复

Since you are using jQuery, you can determine whether a variable is undefined or its value is null by using a single function.

var s; // undefined
jQuery.isEmptyObject(s); // will return true;

s = null; // defined as null
jQuery.isEmptyObject(s); // will return true;

// usage
if(jQuery.isEmptyObject(s)){
    alert('Either variable: s is undefined or its value is null');
}else{
     alert('variable: s has value ' + s);
}

s = 'something'; // defined with some value
jQuery.isEmptyObject(s); // will return false;
csdnceshi75
衫裤跑路 Not work detect jquery is error prntscr.com/h7pq4b
接近 3 年之前 回复
weixin_41568183
零零乙 This does not work with number
4 年多之前 回复
weixin_41568134
MAO-EYE This did not work for me. I still got the error: ReferenceError: s is not defined for the first example.
4 年多之前 回复

i run this test on chrome console, using (void 0) you can check undefined

var c;
undefined
if(c === void 0)alert();
// output =  undefined
var c = 1;
// output =  undefined
if(c === void 0)alert();
// output =   undefined
// check c value  c
// output =  1
if(c === void 0)alert();
// output =  undefined
c = undefined;
// output =  undefined
if(c === void 0)alert();
// output =   undefined

I've just had this problem i.e. checking if an object is null.
I simply use this:

if (object) { Somecode}

i.e.

if (document.getElementById("enterJob")) 
  document.getElementById("enterJob").className += ' current';
csdnceshi77
狐狸.fox It works, so no ambiguity there. :)
4 年多之前 回复
csdnceshi61
derek5. it would be better to set var A = document.getElementById("enterJob") if(A)A.className+= ' current'; this way you do 50% work for same result... But maybe you just did it for shows and then I salute.
接近 7 年之前 回复
共25条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐