0
var x = {};
x.a = {y:5};
x.b = {z:6};

for (prop in x) console.log(typeof prop); // returns "string". Why not "object"?

Shouldn't it return object? How do I get around this?

2

4 Answers 4

1

If you output the prop's themselves, you'll see they are the keys: "a", "b".

Sign up to request clarification or add additional context in comments.

3 Comments

The values that prop gets in the loop are the string "a", and then the string "b".
Right, but why does it get the string when "a" is an object?
@user1019031: "a" is not an object, it is a string. x.a (or x["a"]) is an object. Have a look at the documentation I linked to in my comment.
1

all of these responses are right, but perhaps you would see it better with a corrected example:

var x = {};
x.a = {y:5};
x.b = {z:6};

for (prop in x) console.log(typeof prop); // returns "string"
for (prop in x) console.log(prop); // returns "a", then "b"
for (prop in x) console.log(typeof x[prop]); // returns "object"
for (prop in x) console.log(x[prop]); // returns {y:5}, then {z:6}

1 Comment

Ah got it thank you! Just what I needed to get my head around it.
0

Its returning the name of the properties.

Comments

0

Change your last line to

for (prop in x) console.log(typeof x[prop]);

The x[prop] part takes the property name, called prop (it is of type string) and returns the property x.prop, which for the case of a and b, will return object.

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.