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.

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.

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.