Why it works only with languages[x] not also with languages.x


#1

Please look at If arguments in the code. Why it is not working if I change with if (typeof languages.x)

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

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

`


#2

because your for in loop stores the values in x as string

this works:

languages.english

this doesn't:

languages."english"

because x contain string values associative arrays notation (square brackets) must be used


#3

yes your example exactly what I tested. I did not know that x in for loop stores string.
That figures. Thanks a lot.


#4

if you really want to dive deeper into this, you have to read something like this:

https://www.quirksmode.org/js/associative.html

to understand how objects and associative arrays are the same, JS has this very different implemented then many other languages


#5

Thanks a lot stetim94. Really appreciate that.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.