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
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.