mtyson
mtyson

Reputation: 8550

Javascript: typeof shows 'object', then null pointer thrown

Maybe someone can shed light on this.

I'm getting JS's version of an NPE on occasion, even though logging shows that typeof the offending variable is 'object'.

Here's the logging:

typeof myVar: object
ERROR in main._getFolderCount(): TypeError: myVar is null
console.error("ERROR in main._getFolderCount(): " + e); 

Here's the code:

try{
  console.log('typeof myVar: ' + typeof myVar);
  if (typeof myVar !== 'undefined' && typeof myVar !== 'null'){
    if (currentMsgsObj && currentMsgsObj.folderId == data[i].id && myVar.totalRows!=data[i].count) {        
      myVar.totalRows=data[i].count;
    }
  } else { 
  }
  } catch (e) {
    console.error("ERROR in main._getFolderCount(): " + e);
  }
}

So you can see that the logging shows myVar is typeof 'object', and the code appears to pass the 'undefined/null' check, and then proceeds to blow up when a myVar member is accessed.

Upvotes: 2

Views: 344

Answers (2)

alex
alex

Reputation: 490183

The null type is spec'd to return object when using the typeof operator upon it.

Upvotes: 3

Tikhon Jelvis
Tikhon Jelvis

Reputation: 68152

In JavaScript, typeof null == 'object'.

You can check whether something is null using ===:

if (blarg === null) ...

Using typeof blarg == 'null' will never work.

Upvotes: 2

Related Questions