Question about scope in 4&5/6. Building an Address Book


#1

In lessons four and five of Building an Address Book, you are instructed to declare variables for the length of the contacts array inside the list and search functions. My question is why? The contacts array is a global variable and can be accessed inside my functions without issue. In 4/6 I didn't bother declaring the contactsLength variable for my list function, and I passed all the same.

This is the reset code for 5/6 for reference.

var bob = {
    firstName: "Bob",
    lastName: "Jones",
    phoneNumber: "(650) 777-7777",
    email: "bob.jones@example.com"
};

var mary = {
    firstName: "Mary",
    lastName: "Johnson",
    phoneNumber: "(650) 888-8888",
    email: "mary.johnson@example.com"
};

var contacts = [bob, mary];

function printPerson(person) {
    console.log(person.firstName + " " + person.lastName);
}

function list() {
	var contactsLength = contacts.length;
	for (var i = 0; i < contactsLength; i++) {
		printPerson(contacts[i]);
	}
}

/*Create a search function
then call it passing "Jones"*/

Thanks for any insight in advance!


#2

Hi @hleighton,

You are absolutely correct! :smiley: This is a bad design decision by the course writer, nothing more. There should definitely be a code refactoring exercise at the end which should aim to improve the user's code by removing such anomalies.


#3

Hello! thank you for asking this question, I had the same yesterday and read all of this part again to find out why? :slightly_smiling:


#4

@gaurangtandon, thanks for the confirmation! :smiley:. I absolutely agree with you on a refactoring course!