Question

my problem is that I want to print out only the properties of my object which are strings. but when I check for the type of the property it's returning string also for a number..

Here's my code:

var languages = {
    english: "Hello!",
    french: "Bonjour!",
    notALanguage: 4,
    spanish: "Hola!"
};

for(var prop in languages){
    console.log(typeof prop);   
}

The output is:

string
string
string
string

I'm sure it's just an easy to solve issue but I can't understand why typeof returns string for the property notALanguage...

Was it helpful?

Solution

prop will be a string representation of the property name.

You want to test typeof languages[prop]

OTHER TIPS

When you use for var .. in .. you're iterating over the keys. Therefore it's effectively doing:

console.log(typeof 'english');
console.log(typeof 'french');
console.log(typeof 'notALanguage');
console.log(typeof 'spanish');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top