-1

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?

Kyoma
  • 209
  • 3
  • 11
  • *"either using `languages.key` or `languages["key"]`"* – yes, but you don't have either of those. You have `languages[key]`. – JJJ May 16 '17 at 07:59
  • `language.i` is equal to `language["i"]` and not `language[i]` – Rajesh May 16 '17 at 08:00
  • This will help: http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets – Rajesh May 16 '17 at 08:01
  • var languages = { english: "hello" } You need to write languages.english i.e specify the key if you console languages.i in your case it will be undefined. The Object;s values can only be accessed through obj.keys (type the actual key) or obj['key']. Likewise Arrays in javascript can be accessed either through number or string example Array['0'] or Array[0] since array are regular Objects – shaunak1111 May 16 '17 at 08:20

1 Answers1

1

The reason why languages.i does not work is because it is equivalent to languages["i"]. In other words, it uses the name "i" instead of the value of i.

Peter B
  • 22,460
  • 5
  • 32
  • 69