Contact List using JavaScript

I’m in the process of completing the JavaScript course on Codecademy and am on the Contact List exercise.

This is the code I finished with to list contacts:

var friends = {
    bill: {
        firstName: "Bill",
        lastName: "Gates",
        number: "212-234-2532",
        address: ["One Microsoft Way", "Redmond", "WA", "93843"]
    },
    steve: {
        firstName: "Steve",
        lastName: "Jobs",
        number: "(765)-756-5676",
        address: ["Three Apple Creek", "San Francisco", "CA", "90210"]
    }
};

var list = function (friends) {
    for (var key in friends) {
        console.log(key);
    }
}

var search = function(name) {
    for (var key in friends) {
        if(friends[key].firstName === name) {
            console.log(friends[key]);
            return friends[key];
        } 
    }
};

The last step in the Contact List exercise asks you to

Try calling both your functions, adding additional friends, changing the fields you include for each friend, and more to customize your new object.

We did some basic logging of your contact list to the console, but we could have made it look even nicer. How might you format the output to look like this?

First Name: Steve
Last Name: Jobs
Number: (408) 555-5555
Address: 1 Infinite Loop
         Cupertino, CA 95014

This is a solution posted in the forum that I’ll have to dissect and study:

var format = function(obj){
    var str = "";
    if (obj.length){
        str = "\nThe name, "+obj+", was not found.";
    } else {
        str += "\nName:    "+obj.firstName+" "+obj.lastName;
        str += "\nNumber:  "+obj.number;
        str += "\nAddress: "+obj.address.join(', ');
    }
    console.log(str);
};

\n
This is known as an escape sequence that tells console.log() to insert a newline character. This is what gives each entry its own line on the display.

if (obj)
In a conditional, a plain object, {} will cast to a Boolean true. This is what is known as a true value, even though it is actually not a value. The main thing is that if obj is not an object, then it is undefined, so false, as in a false value.

if (obj.length)
A plain object does not have a length property. Only strings and arrays do. Since a not found return value will be a string, it passes. An object does not.

array.join(', ')
As we can see, the join() method is a property of the Array object that converts an array to a string. The argument, (‘, ‘) supplies the separator, in this case, comma space.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s