7

I am reading the book "JavaScript for web designers" and I've come to this example:

var fullName = {
  "first": "John",
  "last": "Smith"
};
for (var name in fullName) {
  console.log(name + ": " + fullName[name]);
}

The output is:

"first: John"
"last: Smith"

What I don't get is: where do I tell the program to get the string "first" and "last". I mean, cycling the object "fullName", I fail to see how "name" can be related to "first" and "last". I hope this is clear. Can you help? Many thanks!

1
  • 1
    the for loop iterates over the keys of your object (which get stored in name) and you then access the corresponding values like normal (fullName[name]) Commented Oct 13, 2016 at 22:04

5 Answers 5

13

for..in iterates over the keys of an object. You can then access an objects values by name using brackets.

var obj = {
  a: 1,
  b: 2,
  c: 3
};

for (var key in obj) {
  console.log('Key:', key);
  console.log('obj[key] == obj["' + key + '"] == obj.' + key);
  console.log('obj.' + key + ' == ' + obj[key]);
}

Sign up to request clarification or add additional context in comments.

Comments

6

It's pretty simple to learn and/or understand. You're looping through all of the properties in the object fullName. For each property, you're giving it the temporary name/alias of name

So you could change it to for (var anything in fullName) and then in the body of the for loop you would reference each property by the name anything like so:

for (var anything in fullName) {

    // anything is an alias for the current property your on of the object you're looping through
    console.log(anything + ": " + fullName[anything]);

}

Comments

3

A for..in loop will iterate through the object's keys. If you use this on an array, then it (most browser engines) will convert the array into an object behind the scenes (read more on Dictionary Mode) and iterate the keys.

You can view the keys by using

var fullName = {
  "first": "John",
  "last": "Smith"
};
console.log(Object.keys(fullName));

And essentially the result of this call is then iterated. Keep in mind that using for..in does not guarantee order of the key value pairs.

Comments

3

in the above code name represent key of the object,

first and last are both keys in the object. and can be used to access the value in the object.

like in the first run of the loop it will be something like this

for("first" in fullName) {
 console.log("first" + ": " + fullName["first"] //John);
}

Comments

2

When you loop through an object, you iterate through the keys. The keys of this object are first and last. Refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in for more information.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.