How properties are being access in this code while printing name of bob and mary?

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];

// printPerson added here
var printPerson = function(person){
console.log(person.firstName + " " + person.lastName);
printPerson (contacts [0]);
printPerson (contacts [1]);
// result is

Bob Jones
Mary Johnson

I do not understand how name of both is access by using person.firstName & person.lastName.
As person is just a perimeter of printperson function which had no prior relationship with name…

var contacts is an array of two objects, bob and mary.
Calling a function printPerson(contacts [0] ); means printPerson(bob);
and that means: console.log(bob.firstName + " " + bob.lastName);

You can write your code like this:
var bob = {…}
var contacts = [bob, mary]
var person = contacts[0]
console.log(person.firstName); // will output "Bob"
But you can put part of your code into function
var printPerson = function(person) {
and call that function
printPerson(contants[0]) // will output "Bob"
printPersin(bob) // will output "Bob"
cause contact[0] == bob
and inside your function in time when it executes
person == contact[0]
person == bob


  • the console is able to log the different names because you are calling each contact by its array index .

  • Your contacts array has variables called bob and mary. Bob lives at index [0] (first in array) and mary lives at index [1] second in array.

  • The bob and mary variables have already been declared as objects, containing the key and value pairs of firsName, Last Name.

  • The printPerson variable containes a function that logs the persons first and last name.


  1. you call the printPerson function with the contacts array and an index of that array as an argument. (contacts[0])

  2. The printPerson function then looks in the contacts array at that index that has been passed to it, finds a variable name (bob) in the array.

  3. Your code then looks up bob within your code and finds an object, and then looks in that object for the properties required as per printPerson.

  4. if firstName and lastName are key and value pairs, the code will console log as per printPerson.

In this case the contacts array is simply an index of names to be able to look up seperate objects within your code. Once the object is found, the key and value can be retrieved.

Hope that makes sense!


Thanx everyone for explanation…
Thank you Mark for your detail explanation

1 Like