0

I want to check if my json data is null/undefined. I have the following code but it seems to skip the checking and go straight to the else.

if (events === null) {
    container.append(nano(nogig));
} else {
    events[0].start.good_date = good_date(events[0].start.date);
    container.append(nano(template, events[0]));
}

Line 385 on this JSfiddle

http://jsfiddle.net/5WQxq/

Amir Afghani
  • 37,814
  • 16
  • 84
  • 124
redditor
  • 4,196
  • 1
  • 19
  • 40
  • why are you using === rather than ==? – Kritner Jul 05 '14 at 02:13
  • 3
    @Kritner: See [this](http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons) to understand why. – djikay Jul 05 '14 at 02:15
  • right, but how can the type of a "null" ever be equivalent to (events)null without some sort of conversion being done on events? With the === operator your objects are compared as is yes? As the boolean said that should get you the expected results. Also read: http://stackoverflow.com/questions/5113374/javascript-check-if-variable-exists-is-defined-initialized-which-method-is-b i think it touches on pretty much the same issue you've hit – Kritner Jul 05 '14 at 02:37
  • 3
    @djikay: The `==` is the correct solution if he wants to check for both `null` and `undefined`. – cookie monster Jul 05 '14 at 02:47

2 Answers2

3
if (!events) {
            container.append(nano(nogig));
        } else {
            events[0].start.good_date = good_date(events[0].start.date);
            container.append(nano(template, events[0]));
        }

This checks for null and undefined.

Typo
  • 1,875
  • 1
  • 19
  • 32
1

If you use the == operator rather than the === operator then testing against null will also match on undefined. That is undefined == null will return true, while undefined === null will return false. So try this:

if (events == null) {

Demo: http://jsfiddle.net/5WQxq/1/

Alternatively you can explicitly test for both values:

if (events === null || events === undefined) {

Or you can just test for a falsy value:

if (!events) {

(...which would also match on false, 0, empty string, and NaN, but those values aren't likely to apply and in any case if they did occur you'd still want the if case to match.)

nnnnnn
  • 147,572
  • 30
  • 200
  • 241