Why not? 5/6 Building and Address Book


#1

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"*/
function search(lastName) {
var contactsLength = contacts.length;
for (var i = 0; i < contactsLength; i++) {
if (contacts[i].lastName === lastName){
printPerson(contacts[i]);
}

}

};

search("Jones");

Why do we have to define var contactsLength = contacts.length

to use contactsLength in (var i = 0; i < contactsLength; i++)

rather than using contacts.length directly like this --> (var i = 0; i < contacts.length; i++)??

Thanks!!!


#2

@malmn,

The only reason is, because the course creator wanted you to do it like that.

You could have used

 for (var i = 0, contactsLength = contacts.length; i < contactsLength; i++) {
 }

#3

Ok thanks! Much appreciated.


#4

Hold on... you mean can add contactsLength = contacts.length in the for loop without having to define it first?
--> contactsLength = contacts.length


#5

@malmn,
You can =declare= anything in the so-called initialization expression.....

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for

for ([initialization]; [condition]; [final-expression]) {
       statement
}

#6

Interesting. Thanks again!