0

I understand why you would want to test for both null and undefined in javascript:

var declared;
...
if ('undefined' !== typeof declared && null !== declared) {
    // do something with declared
}

or

function doSomethingWithDefined(defined) {
    if ('undefined' !== typeof declared && null !== declared) {
        // do something with declared
    }
}

Is there a way to shorten this statement? It's pretty verbose pattern.

JoBu1324
  • 7,751
  • 6
  • 44
  • 61
  • 1
    Wrap it in your own function? Also, have you read [this post?](http://stackoverflow.com/questions/5113374/javascript-check-if-variable-exists-is-defined-initialized-which-method-is-b) – Lix Aug 03 '13 at 20:31
  • 1
    @Dave If `var == 0`, then `!var` is true. – xanatos Aug 03 '13 at 20:36
  • 1
    In the title you state that you want to test whether a variable is declared. In the actual question you want to test whether a variable is `undefined` or `null`. What is it now? A variable is declared when it is defined with `var foo` somewhere. `undefined` and `null` are values an existing variable can have. Depending on what you want, the code can be shortened or not. – Felix Kling Aug 03 '13 at 20:39
  • Good point, Felix. I'll clarify the title. – JoBu1324 Aug 03 '13 at 20:42
  • Still not 100% clear to me (regarding the content of the question). Does this mean that `declared` might not exist? Or does it always exist and you just want to test whether it has a value other than `undefined` and `null`? – Felix Kling Aug 03 '13 at 20:45
  • Unfortunately there's no single solution that fits all use cases. – Fabrício Matté Aug 03 '13 at 20:46
  • I see the nature of your question now, Felix. I'm assuming that `declared` exists in the current scope. – JoBu1324 Aug 03 '13 at 20:52
  • I suggest you take a look at CoffeeScript, the language which addresses specifically such shortcomings in JavaScript. Regarding your question it has `?` postfix operator which can be used like this: `if var? then 'ok' else 'nope'` – andreypopp Aug 03 '13 at 20:54
  • In that case `variable != null` will be `true` if `variable` is either `null` or `undefined`. The `typeof` test is only necessary if you are not sure whether the variable exists. – Felix Kling Aug 03 '13 at 20:56
  • 1
    Why not test that `declared` is what you expect instead? For example `if (typeof declared === "string")` – Xotic750 Aug 03 '13 at 20:56
  • @andreypopp, and in coffeescript `a?` compiles to `typeof a !== "undefined" && a !== null`. – Brigand Aug 03 '13 at 20:57
  • 1
    possible duplicate of http://stackoverflow.com/q/5113374/218196. – Felix Kling Aug 03 '13 at 20:59
  • @FakeRainBrigand exactly! – andreypopp Aug 04 '13 at 00:04
  • @FakeRainBrigand besides that `a?()` compiles to `if (typeof a === "function") { a(); }` and `a?.b` compiles to `if (typeof a !== "undefined" && a !== null) { a.b; }`. – andreypopp Aug 04 '13 at 00:06

1 Answers1

3

If you define a variable like this:

var defined;

It has no value, but you don't get a ReferenceError, because the reference exists. It just doesn't reference anything. Thus, the following is valid.

if (defined != null) { ... }

In the case of a function, such as this

function doSomethingWithDefined(defined) {
    if (defined != null) { ... }
}

It can be translated to:

function doSomethingWithDefined() {
    var defined = arguments[0];
    if (defined != null) { ... }
}

Because the variable is declared implicitly (but not necessarily defined), you can do this and not get an exception, so there's no need for typeof.

doSomethingWithDefined("value"); // passes defined != null
doSomethingWithDefined(); // defined == null, but no exception is thrown

The typeof operator is usually used when you're not sure if a variable has been declared. However there is an alternative that works for all real world scenarios.

if (window.myvariable != null) {
    // do something
}

Because global variables are the only non-parameter variables you should be concerned about, using property access we can also avoid the exception.


That said, I strongly recommend type checking, rather than type avoiding. Be positive!

Is it a string?

if (typeof declared === "string"){ ... }

Is it an array?

if (typeof declared === "object" && declared.length != null){ ... }

Is it a non-array object?

if (typeof declared === "object" && declared.length == null){ ... }

Is it a function?

if (typeof declared === "function"){ ... }
Brigand
  • 84,529
  • 20
  • 165
  • 173
  • Please provide a case where a non-global, non-parameter variable *may* or *may not* be defined. I can't think of any, but I've been wrong before :-) – Brigand Aug 03 '13 at 21:04
  • I've never considered positive typeof tests before, which makes a lot of sense. I guess I haven't written enough javascript yet ;) I'm going to think about this some more, but this might be the answer I'm looking for. – JoBu1324 Aug 03 '13 at 21:10
  • What's the point of the first two examples? `arguments` has nothing to do with the question and is probably rather confusing than helping. – Felix Kling Aug 03 '13 at 21:16
  • It shows why you don't need to be extra safe and use the typeof operator inside a function. The two are equivalent code. I find that explaining internals dissolves some of the mystery. I'll try to clarify it, though. – Brigand Aug 03 '13 at 21:18