27 Looks For-In To Me


My code is printing out all 4 items in the language object. I don’t understand because it seems like me “typeof” operator should catch it.

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

// print hello in the 3 different languages
for (var x in languages) {
    if (typeof x === "string") {
    else {
        console.log("Not a language")

Thanks in advance for any help


if (typeof x === "string")

first of all consider what is x ?

for (var z in languages) {
    if (typeof languages[z] === 'string') {

The above is the correct way of doing this. (Feel free to rename z to whatever). As rcodeman said (although quite rude imho, despite the point of the whole thing to be teaching us new stuff), your x will always return a string, because x actually is string: returns the name of the property (e.g. “english”, “french”, “notALanguage”, etc.).
So you need to access the typeof of the value of the property (e.g. “Hello!”, “Hola!”, etc.) in order to strict-match it (===) to “string” (or ‘string’ in my example).
Also, if you feel like it, you can add more properties to the languages object since they only check if you manage to print-out (“console.log()”) those first three, but not how many more you print.
Also, note to staff, prolly: I avoided the whole for-in thing by simply using three console.logs printing Hello!, Bonjour! and Hola! :stuck_out_tongue: bit sloppy, eh? hehe :slight_smile:


I have the exact code as you, but it keeps printing out the number 4.


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