Need help with defining variables for 5/6


#1

When i define a variable in a function, is it only defined in the function, for example if I call on the variable anywhere that is outside of the function, will it be undefined? for instanceTHIS IS MY CODE
IT wouuld not log Bob Jones to the console, until finally I defined the var contactsLength = contacts.length outside of the function from which it was originally within. you can see where I added the variable definement out side of the function in between #####"s
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]);
}
}

##########var contactsLength = contacts.length;

var search = function(lastName) {
for (var i = 0; i < contactsLength; i++) {
if(contacts[i].lastName === lastName) {
printPerson(contacts[i]);
};
};
};

search("Jones");

Pleas I really need help to understand if I must define the variable outside of the function in order for it to be global. or is it just local if it is in a function. Or did i maybe just answer my own question??? Haha lol. Please let me know if I answered my own question correctly. Thank you so much