1

I am always unsure about which one is correct and which ones to use.

Usually I do (obj == null) check. I thought its better to just ask.

Which one of the following shall I use:

  if (obj == null) {
        alert('obj is null');
  }

OR

  if (obj == null || obj == 'undefined') {
        alert('obj is null or undefined');
  }

OR

  if (obj == null || obj == undefined) {
        alert('obj is null or undefined');
  }

OR

  if (obj == null || obj === 'undefined') {
        alert('obj is null or undefined');
  }

Which one is better and do we really need to check for undefined?

Oxon
  • 4,901
  • 8
  • 40
  • 54
  • The third one but with "===" comparison operator always – Akshay Khandelwal Oct 08 '13 at 17:07
  • 6
    this one: `if (typeof(obj) === 'undefined') {}`, otherwise you're checking for value not for existence of the object (if that was your intention that is) – Zathrus Writer Oct 08 '13 at 17:07
  • @ZathrusWriter: No, that's not a good way. Look at OP's last code example. It's one example of the common bugs that comes up when trying to use that syntax. – user2736012 Oct 08 '13 at 17:08
  • Related: http://stackoverflow.com/q/359494/1618257 – David Starkey Oct 08 '13 at 17:09
  • 4
    which one is better **for what**? What are you trying to do? – Karoly Horvath Oct 08 '13 at 17:12
  • Related: http://stackoverflow.com/questions/6429225/javascript-null-or-undefined – nate_weldon Oct 08 '13 at 17:12
  • To sum up: what specifically are you trying to guard against? Are you trying to see if you're referencing a variable that may not exist (almost certainly a bug)? Do you *need* to differentiate between `undefined` and `null`? They're different. – Dave Newton Oct 08 '13 at 17:33
  • To be honest, looking at the answers and comments here I am more confused now than before I posted the question. One thing is obvious that I am not the only one who doesn't know the difference. – Oxon Oct 15 '13 at 15:05
  • @KarolyHorvath I want to check if an object has value or not (i.e. if its not null or undefined.) In other words, I want to check that I will not get an exception if I use this object. – Oxon Oct 15 '13 at 15:06
  • 1) use `obj == null` 2) "I will not get an exception if I use this object." - ehm.. *use* is a quite vague term, obviously this won't prevent *all* exceptions (eg: a method that checks some property of the object could throw an exception...) – Karoly Horvath Oct 15 '13 at 16:59

4 Answers4

1

Just do

if (obj == null) {

That'll check for both null and undefined.


To the confused downvoters, using the == null will simultaneously check for null and undefined, but no other "falsey" values.

The typeof foo === "undefined" syntax actually causes more bugs than it fixes. Like these...

typeof foo === undefined     // common bug

foo === "undefined"          // common bug

typeof foo === "undefnied"   // common bug

These are very common bugs, and are reasons to not use this syntax.


Here are the cases for which beginners are told to use that syntax...

  • undefined may have been redefined

  • your variable may be undeclared, causing a ReferenceError


Here are the reasons that those aren't very good reasons

  • the global undefined can not be redefined in modern browsers, so it's a non-issue. And even if it does get redefined, then something is terribly wrong, and needs to be fixed either way. If you hide the issue, you'll never be able to fix it.

  • If a developer is trying to use an undeclared local variable, that means there's a bug in the code, and the ReferenceError should be seen as a desirable warning, not as something to be hidden.

  • If a developer is trying to use an undeclared global variable that can't be known before hand, it's safer to check for the variable as a property on the window object than to use the unsafe typeof foo === "undefined" syntax.


And yes, there is a type distinction between null and undefined, so both need to be checked. The == operator performs a type coercive algorithm when the types don't match. That's why you can use == null to check for both.

user2736012
  • 3,543
  • 16
  • 13
  • as for this answer, [this jsFiddle](http://jsfiddle.net/tJyfg/) returns: "Uncaught ReferenceError: abc is not defined " – Zathrus Writer Oct 08 '13 at 17:14
  • @ZathrusWriter: Right, that's because your jsFiddle has a bug. Error messages are meant to inform the developer of bugs so that they can be fixed. Developers don't try to hide bugs, they fix them. – user2736012 Oct 08 '13 at 17:15
  • why would `typeof foo === "undefined"` be unsafe or bugged? – David Fregoli Oct 10 '13 at 12:51
  • @DavidFregoli: In my answer I described the common bugs that are encountered when trying to use that syntax. In my years as a JavaScript developer, I've never actually seen someone redefine `undefined`, but I've seen many, many occurrences of the bugs I've described. So because it's an error-prone syntax, it's better to avoid it. *(Not to mention that it's overly verbose and unintuitive.)* – user2736012 Oct 10 '13 at 17:59
  • @user a bug is something that results in erratic or inconsistent behaviour, this is syntax could be called confusing but if you know how to you use it there's nothing bugged about it – David Fregoli Oct 11 '13 at 09:00
  • @DavidFregoli: Please read what I wrote. I didn't say it *is* a bug. I said this syntax *causes* bugs because people get it wrong, and I provided very clear examples. It's verbose, unintuitive, and almost always entirely unnecessary. In spite of this, people insist on its use, which has a strong feel of cargo cult programming. – user2736012 Oct 11 '13 at 13:49
1

You've identified four tests:

if (obj == null)
if (obj == null || obj == 'undefined')
if (obj == null || obj == undefined)
if (obj == null || obj === 'undefined')

Of these, the first and third behave identically. (obj == null will evaluate to true if obj is undefined.)* The second and fourth do not do what you want at all, because the test will succeed if obj is the string 'undefined' (as well as when obj is undefined, thanks to how obj == null behaves).

As to whether you need to test for undefined, that depends on whether you need to distinguish between undefined values and null values. In most applications, you do not need to do that. If you do need to do that, you should be using obj === null and obj === undefined.

If you need to safeguard against undeclared variables, then you can use:

if (typeof obj === 'undefined')

but in all but the most unusual situations, you should know in a given context whether a variable has been declared.

*However, obj === null will evaluate to false if obj is undefined.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

undefined is a word that means not defined.

null is an object

Let see this code

function saySomething(thing) {
    if(thing === undefined) {
        sayRandomThing();
    }else {
        sayThat(thing);
    }
}

In this case I would check if the argument is given or not or, in other words, if the argument is defined or not.

Note that the variable name thing is declared, but it's not defined. So in this case thing === undefined is enough and you don't need to do more verbose typeof thing === "undefined".

There is no reason to use the word null. Because null is an object and it have nothing to do with our thing.

Just another note. typeof thing === "undefined" is needed when effectly you don't know if the variable is declared. But, as documentation say:

However, this kind of technique should be avoided. JavaScript is a statically scoped language, so knowing if a variable is defined can be read by seeing whether it is defined in an enclosing context. The only exception is the global scope, but the global scope is bound to the global object, so checking the existence of a variable in the global context can be done by checking the existence of a property on the global object (using the in operator, for instance)

When should I use null?

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null

In APIs, null is often retrieved in place where an object can be expected but no object is relevant.

null is an object. Javascript core use null when a function should returns an object or an array, but in some case should tell us an "object not found" (different case of an empty object {} that means: I've found the object, it's empty). It's the case of method match for example.

var matches = "My awesome string".match("don't match anything");

console.log(matches === null); // true

In your script, you know, as developer, what type should be the variable. And you should know which condition you should use. Remembering:

  • If you don't know if the variable is declared or not, use if(typeof varName === "undefined") before other checks.
  • If you don't know if the variable is defined or not, use if(varName === undefined) before other checks.
  • If you know if the variable is defined and it's an object, check if is null with if(varName === null)

The strict equality operator (===) is needed because varName == undefined also checks whether varName is null

Luca Rainone
  • 16,138
  • 2
  • 38
  • 52
-1

Please use the following if you want to check for the existence of the object in question and prevent various JS erorrs:

if (typeof(abc) === 'undefined') {
    console.log('not defined');
}

jsFiddle proving the usefulness: http://jsfiddle.net/tJyfg/1/

If you're looking to check a global variable, then the following will do the trick without using typeof() (works for all objects as well)...

if (!window.abc) {
  console.log('not defined');
}
Zathrus Writer
  • 4,311
  • 5
  • 27
  • 50
  • This doesn't do what OP wants. And that verbose and clunky syntax is the source of far more bugs than it supposedly "avoids". It's a bad practice overall. – user2736012 Oct 08 '13 at 17:16
  • @ZathrusWriter I agree with your comment regarding the _existence_ of an object. But I think the OP is checking for an assigned value. This check doesn't work if say `var abc = null;` – thgaskell Oct 08 '13 at 17:17
  • @user2736012: really? what does the OP want? – Karoly Horvath Oct 08 '13 at 17:17
  • @KarolyHorvath: Obviously to test for `null` or `undefined`. – user2736012 Oct 08 '13 at 17:17
  • @user2736012: yeah. "obviously". – Karoly Horvath Oct 08 '13 at 17:18
  • @KarolyHorvath: Yes, it's very obvious from the question. – user2736012 Oct 08 '13 at 17:18
  • yeah, the thing is there is no context for this, so I assumed we're checking for the definition of that variable, not value... I'd not answer like this otherwise... obviously :D – Zathrus Writer Oct 08 '13 at 17:20
  • @ZathrusWriter: Thanks for the downvote, but my answer is correct, as is my comment. If your program is trying to use an undeclared variable, it's a bug that should be fixed. Error messages are not the enemy... faulty code is the enemy. Noobs have trouble understanding this. – user2736012 Oct 08 '13 at 17:21
  • 1
    Note that if you're in a Web Worker, 'window' also won't be defined. You can use self.abc ... but typeof(abc) === 'undefined' will work in both cases. It will also cover other environments like node.js. – dlongley Oct 08 '13 at 17:22
  • @ZathrusWriter: I didn't downvote you. Would you like me to do it now as proof? – user2736012 Oct 08 '13 at 17:24
  • @user2736012 someone here is having multiple accounts and downvoting what they don't like on answers of others - I don't like that guy, whoever you are\ – Zathrus Writer Oct 08 '13 at 17:26
  • @ZathrusWriter: Why do you think it would be someone with multiple accounts? IMO, yours ought to be downvoted, because it's not also checking for `null`, which is what OP is asking about. – user2736012 Oct 08 '13 at 17:29