27. Looks For-In to me - does not work!


#1

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

// print hello in the 3 different languages
for (var key in languages) {
if (typeof languages.key === "string") {
console.log(languages.key);
}
}

it doesn't print out anything


27. Looks for-in to me
#2

It should look like this

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

// print hello in the 3 different languages
for (var key in languages) {
  if (typeof languages[key] === "string") {
    console.log(languages.key);
  }
}

You did something else. Your key is not a string so it printed nothing.


#3

JavaScript syntax will be my downfall because I just don't get it. For me, it's a try this and if that doesn't work try that. I had the code written above by "igorcaletacar" but couldn't get it to work. I kept getting 3 lines printed with "undefined" . Finally I had an inspiration and changed : console.log(languages.key); to console.log(languages[key]). It worked! Hope this helps somebody :slightly_smiling:


#4

The reason languages.key didn't work and languages[key] worked is because dot notation is literal and bracket notation can use variables.

Further Reading...


#5

What threw me for a loop (JavaScript pun intended) is how the program knew to identify the data type "string" by name.


#42