undefined
undefined

Reputation: 2101

Does JavaScript's typeof function check for null

Does javascripts typeof expression check for null?

var test = {};
console.log(typeof test['test']);//"undefined"

var test = null;
console.log(typeof test['test']);//TypeError: test is null

Obviously, but why the error, if typeof null is an object?

EDIT:
I know how to avoid the type error, and that null has no properties, but I'm wondering is there an explanation to the behavior of typeof.

Upvotes: 2

Views: 100

Answers (4)

suff trek
suff trek

Reputation: 39777

You can try you test as

typeof (test && test['test']) 

this way you avoid TypeError

Upvotes: 0

Daniel Robinson
Daniel Robinson

Reputation: 14848

you're asking it to read the property "test" of null which makes no sense, the error is basically telling you "test is null -> can not read property "test" of null".

you should just be doing typeof test instead of typeof test['test'], I'm not sure why you're doing it the latter way.

Upvotes: 0

Justin Ethier
Justin Ethier

Reputation: 134167

The problem is that you are trying to access an element of test, but test is null and NOT an array/object. So the following code throws an error: test['test'].

The typeof would work fine if you passed it null directly. For example, using the node.js console:

> typeof null
'object'

Upvotes: 1

karaxuna
karaxuna

Reputation: 26930

var test = { test: null };
console.log(typeof test['test']);// will be object

Your code throws exception because you are reading property of null like this:

null['test']

Upvotes: 5

Related Questions