Reputation: 2101
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
Reputation: 39777
You can try you test as
typeof (test && test['test'])
this way you avoid TypeError
Upvotes: 0
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
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
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