Contact list? Cant understand the for/in loop


var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "Gates",
friends.steve = {
firstName: "Steve",
lastName: "Jobs",
var list = function(Obj){
for (var anything in Obj){
var search = function(name){
for (var anything in friends){
if (friends[anything].firstName = name){
return friends[anything]

This is my code. I cant understand the for/in loop. How does it work and what does it do? And i also do not understand the list function and why is it necessary.


@ajaxjumper52610 the list function is just there to display all of the properties attached to that object. the for/in loop is used to loop through all of the properties that an object has. you can use it to search for a specific property or value, or to display a specific property or value. the counter variable -- anything in your loop -- takes on each subsequent property of the object mentioned, each time the loop is executed, until it gets to the last property of that object, then the loop quits.


The list() function has one purpose... To list the primary key names of an object.

var list = function (object) {
    for (var key in object) {

Given an object,

var friends = {
    bill: {},
    steve: {}


A statement treats a JavaScript object as an Associative Array with string index and associated value pairing. The iterator variable is dynamic, taking on one key name in each iteration.

In the above, key was first 'bill' then 'steve'.

Your search() function looks correct except for two things:

  1. ... = name should be ... === name
  2. The call should search for a data value, not a key... search("Bill");