Question of Property and Variable scopes


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

search("Jones");

My code works perfectly, but I have a question on why it works.

At the top when the two objects are declared, they both have properties of "lastName"
Under the function at the bottom called "search", one of its parameters is also called "lastName". Within the function "lastName" is being also called as both a property and parameter/variable.

So my question is: Does the scope of property names not conflict with the name of a variable? I know that you can have multiple objects with the same property, but can you have a property and a variable with the same name?
For example would this be correct to use:

var name = "whatever";

var title = {name: "me"};

var name = title.name;

console.log(name);  // should this now print out "me" to the console?

#2

I believe your last piece of code verifies your understanding. Well done on devising a test that answers your question.


#3

Awesome! Thanks. I just wanted to make sure that I wasn't making up syntax rules by myself.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.