3/6 is person defined?


#1

Hi - reposting this question (from austinyang91) from the old message board, as it wasn't answered and has confused me too...

Hi in the hint it suggest that:

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

My question is how can you use "person.firstName" if "person" was never defined above? How does the code recognize these names to be "person" but not other objects?

In previous lessons, we learned about using constructor. You name your object type in the very beginning so that would make sense. But how does it work with literal notation? Does it just pick it up as a person as I use the Dot notation? Does that mean I can write anything else then it would still pick it up?


#2

Constructor and literal notation both create the same kind of object.

new Object() is identical to  {}

And you can edit both by dot or square bracket notation (you got this one already, did you?). The difference is just that for this use of the constructor notation you have to use dot notation as your objects comes empty when created (we later learn to build our own constructors that can create objects with properties). For literal notation you can fill it when you create it but you could as well access and extend it via dot notation.

Now to person.

My question is how can you use "person.firstName" if "person" was never defined above?

Well it is declared as the parameter of your printPerson function. So the interpreter already knows this name and as dot notation is used on it, it is assumed that there is an object inside of it. Now we assume that the user is friendly and really passes objects by printPerson(nameOfAnObject); because otherwise we might get undefined or and error.


#3

Got it - thanks for explaining


#4

Thanks for re-asking this. I find it really weird. So much of coding depends on really accepting that the computer never assumes anything, and never just instinctively "knows" what you want - but here, that seems to be the case. It's hard to process.