Property Name VS Property Value


#1



I kinda mess it up in an exercise, but as you probably heard, it sometimes take 99 mistakes to get the right answer... or something like that ¬¬.

Thing is, you can print the name of a property, instead of just printing their value.

printing the name of the properties.

Code:

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

// print hello in the 3 different languages

//this prints the properties names:
for(var prop in languages) {
    if(typeof prop === "string") console.log(prop);


Output:

english
french
notALanguage
spanish

This, instead, prints the properties values, or more specifically, the language values.

Code:

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

//this prints the properties values
for(var prop in languages) {
    if(typeof languages[prop] === "string") console.log(languages[prop]);
}

Output:

Hello!
Bonjour!
Hola!

Does anybody knows how this works?
How and when can we get a key, value pair?
Is this limited to objects?

Thanks.


#2

i am confused by your question. You have an object called languages. This objects contains keys (english french and so on) and values (Hello!,Bonjour! and so on)

with a for in loop you will get the keys:'

for(var prop in languages) {
  console.log(prop);
}

then you can use the the square bracket notation to access the values of these keys:

for(var prop in languages) {
  console.log(languages[prop]);
}

you can get the key, value with objects and associative arrays, which in javascript are the same


#3

Thanks, I'm new in Javascript. I discover I can print the name of a property name by accident.

Do this makes sense?

var i = 0;
var namePropertyArray = [];
for(var prop in languages) {
    console.log(prop + ": " + languages[prop]);
    namePropertyArray[i] = prop;
    i++;
}

#4

why the namePropertyArray? why not simple do:

for(var prop in languages) {
    console.log(prop + ": " + languages[prop]);
}

the for in loop takes care of most of the work for you


#5

Ok, yup, that makes a lot more sense,
but I can still store the properies name in the array if I want to?


#6

yep, you can. Either use the associative array notation:

languages['dutch'] = "Hallo!";

or the object notation, which i would use:

languages.dutch = 'Hallo!';