I was given this code:
var languages = {
english: "hello",
french: "bonjour",
notALanguage: 4,
spanish: "hola"
};
I have to print out the 3 ways to say hello. I did this:
for (var i in languages) {
if (typeof(languages.i) === "string") {
console.log(languages.i);
}
}
However, it did not work. On the other hand, this worked:
for (var i in languages) {
if (typeof(languages[i]) === "string") {
console.log(languages[i]);
}
}
Why? There are two ways to access a property value: either using languages.key or languages["key"]. So why did my code fail, and why did the other code pass?