- Defining Variables
- Functions
- Scope
- Loops
- Conditionals
- Putting It All Together
- Summary
- Exercises
Putting It All Together
Up to this point in the chapter, you have been building a simple address book and outputting the data.
Listing 6.6 is a cumulative dump of the code you’ve been putting together. It contains the JSON object with contact information, an anonymous function, and a loop with a conditional statement to check the JSON object length.
Listing 6.6. Application Code
/* create some data in the form of a JSON object you can consume and loop through */ var contacts = { "addressBook" : [ { "name": "hillisha", "email": "hill@example.com", }, { "name": "paul", "email": "cleveland@example.com", }, { "name": "vishaal", "email": "vish@example.com", }, { "name": "mike", "email": "grady@example.com", }, { "name": "jamie", "email": "dusted@example.com", } ] }; /* wrap everything in an anonymous function to contain the variables */ (function () { /* cache some initial variables */ var object = contacts.addressBook, // save the JSON object contactsCount = object.length, // how many items in the JSON object? "5" target = document.getElementsByTagName("body")[0], // where you're outputting the data i; // declare the "i" variable for later use in the loop /* before doing anything make sure there are contacts to loop through */ if(contactsCount > 0) { /* loop through each JSON object item until you hit #5, then stop */ for (i = 0; i < contactsCount; i = i + 1) { /* inside the loop "i" is the array index */ var item = object[i], name = item.name, email = item.email; target.innerHTML += '<p><a href="mailto:'+ email +'">' + name + '</a></p>'; } // end for loop } // end count check })(); // end anonymous function
There’s the address book application as it stands right now. You’ve created the contact information for our five friends and inserted them into a JSON object. After storing the JSON object, you’re looping through each item (person) and outputting them individually into the <body> element, one after another. You’re also creating HTML fragments that are paragraphs and mailto links for each person.
The processes of looping through data, storing the items as variables, and outputting them into the DOM is, by far, the most common looping method you will see as you build more applications with JavaScript. This code will not only serve as a base for our application, but as a good reference point for your future JavaScript development.