Benny Thadikaran Benny Thadikaran - 1 year ago 99
Javascript Question

Codeacademy -listing everybody- returning undefined

I wrote this code as part of CodeAcademy javascript course. The code creates two objects 'bob' and 'mary' and assigns them to 'contacts' array.

The 'list' function loops through the 'contacts' array and returns the firstName + lastName utilising the 'printPerson' function

Below is the result i get from running the code:

Bob Jones

undefined --> cant figure out why undefined?

Mary Johnson


2 --> contacts.length - shouldnt this read 1?

var bob = {
firstName: "Bob",
lastName: "Jones",
phoneNumber: "(650) 777-7777",
email: ""

var mary = {
firstName: "Mary",
lastName: "Johnson",
phoneNumber: "(650) 888-8888",
email: ""

var contacts = [bob, mary];

function printPerson(person) {
console.log(person.firstName + " " + person.lastName);
var list = function() {
var contactLength = contacts.length
for (i = 0; i < contactLength; i++) {

Answer Source

In your loop you're calling console.log(printPerson(contacts[i]));

JavaScript will at first ignore the console.log() part and start with evaluating the inner part, printPerson(contacts[i]). It's a function call, so JS calls the function, which logs "Bob Jones" to the console. Then, since the function doesn't return anything, the function call is evaluated as undefined.

Next, JS returns to the ignored part, plugs in the evaluated expression and runs the command: console.log("undefined")

To avoid this you can either return person.firstName + " " + person.lastName; in the function instead of logging it, or you just call printPerson(contacts[i]); in your loop.

The array's length is 2 because it contains 2 elements.