Simple theory behind getting the property name from a for-in loop?
arrays, javascript, loops, object, oop
Solution
I have to admit I don't fully understand the question, but I try to answer as best as I can nonetheless. An object is pretty much comparable a hash (-table). As you know, that consist out of an identifier and a value which is stored behind that identifier.
In ECMAscript, that identifier is the key within an object.
For an Array, there is only one interesting thing you want to receive when looping over it, since its "keys", are just indexed numbers (which in reality are also Strings here, but that just as a sidenote). But, since object keys can be anything, there is a conflict when looping them. Do you want to get the key or the value ?
Thats why there is the `for-in` loop. You're looping over the keys and with that key you might also be access the value behind.
However - you are not fully alone with the confusion. That is why ECMAscript Next will introduce the `for-of` loop for objects, which inverts this logic. Instead of keys you will directly loop over the values.
var obj = { one: 1, two: 2, three: 3 };
for(var value of obj) {
console.log(value); // 1, 2, 3
}
Problem
First of all, I want to say that I'm huge on theory. I don't like abstraction. I want to know how things work before trying to use them. I have been searching everywhere for a simple theory behind getting the property name (not the value) for a for-in loop. I will demonstrate it in code so hopefully someone can potentially explain how it works exactly... ``` var obj = { one: 1, two: 2, three: 3 }; // A basic object instantiated with 3 public properties. for (var prop in obj) { console.log(prop); // logs "one", "two" and "three" ??? } ``` I figured it would evaluate prop variable as 1, 2 and 3 but it logs out the actual property name. I know obj[prop] is what evaluates to the actual value of those properties but this is like an inception to me. prop is a reference that stores another reference? I'm trying to think about this in terms of how variable i in a for loop is kinda like the index of an array. Also what is this and is it similar to what I'm asking? ``` var obj = { "one": 1, "two": 2, "three": 3 }; ``` How are the property names strings?... You can't say var "string" = "Hello, World!"; as thats illegal.