2

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.

4
  • because the first test is null Commented Jul 17, 2013 at 13:33
  • 1
    null has no "test" member, attempting to accessing it is illegal Commented Jul 17, 2013 at 13:34
  • 3
    the issue is you're trying to read the val of null['test'] Commented Jul 17, 2013 at 13:34
  • 1
    You can check the typeof null, but you can't access a property of null, as null has no properties. Commented Jul 17, 2013 at 13:36

4 Answers 4

5
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']
Sign up to request clarification or add additional context in comments.

1 Comment

In fact, you could have a line that just says: "test['test'];" (no actual action with the value) and it would still throw an error.
1

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'

Comments

0

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.

Comments

0

You can try you test as

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

this way you avoid TypeError

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.