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

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

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.

13 Likes

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 :slight_smile:

32 Likes

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…

14 Likes

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

5 Likes