0

Im brand new to javascript, and relatively new to programming as a whole. I've been understanding the mechanics of javascript, but im stumped however in a situation like the following:

var dataTypes = {
 string1: "Test",
 string2: "Test",
 number1: 4,
};
console.log(typeof dataTypes.number1);
console.log(" ");
for (var x in dataTypes) {
 console.log(typeof x);
 if ((typeof x) === "string") {
 console.log(dataTypes[x]);
 } else {
 //
 }
}

And when I run this, my console displays the following:

number 
string
Test
string
Test
string
4

I'm so confused how dataTypes.number1 went from being a number data type to a string. If anyone could take the time to elaborate what i have done wrong, and explain, that would be wonderful.

Alnitak
341k72 gold badges420 silver badges503 bronze badges
asked Mar 16, 2015 at 16:21

1 Answer 1

8

Your variable x is the key (rather than the value) associated with each key/value pair in dataTypes. Is is therefore always a string.

You need to examine typeof dataTypes[x] instead.

answered Mar 16, 2015 at 16:22
Sign up to request clarification or add additional context in comments.

2 Comments

thanks! I feel silly that I overlooked that now haha.
@ColtraneNadler you can formally accept Alnitak's answer, if it's the right answer.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.