We made a friend--why no "this"?


#1

https://www.codecademy.com/en/courses/building-an-address-book/0/6?curriculum_id=506324b3a7dffd00020bf661#

Just wondering why you don't have to do firstName: this.firstName, etc. My code is right, but I am confused on why you don't have to use "this."

Replace this line with your code.


#2

we never use this when adding properties to an object?


#3

This will get tricky but here we go:

firstName: firstName

The left hand firstName is a new property we are adding to our new object. The right hand firstName is a parameter that was provided to the addContact function.

Already its a little repetitive, but if you were to refer to the right hand firstName as this.firsName you are actually referring to the left hand value's firstName property, which is being assigned by the value referencing itself. Kind of like when you stand in between two mirrors and it seems like an infinite hallway.

In modern JavaScript we have a shorthand for property assignment.

function add(firstName, lastName, phoneNumber, email) {
    contacts[contacts.length] = {
        firstName,
        lastName,
        phoneNumber,
        email
    }
};

If the property you're declaring has the same name as the parameter you're assigning it to then you can just list it in the object literal. It helps to streamline an otherwise redundant assignment process.


#4

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