Kindly explain working of function 'printPersonName' in the code.I am not clear with how this function works?


#1



https://www.codecademy.com/courses/objects-ii/2/3?curriculum_id=506324b3a7dffd00020bf661


function Person(name, age) {
    this.name = name;
    this.age = age;
}
// a function that prints the name of any given person
var printPersonName = function(p) {
    console.log(p.name);
};

var bob = new Person("Bob Smith", 30);
printPersonName(bob);

// make a person called me with your name and age
// then use printPersonName to print your name
var me = new Person("Anushree", 28);
printPersonName(me);


#2

when you call the function:

printPersonName(bob);

you pass as argument bob (bob is your newly created object), now inside your function the object is stored in the variable p, the function parameter:

var printPersonName = function(p)

so now p.name will log the name, p would have list the entire object, p.age would have logged the age


#3

Is this 'p.name' similar to 'bob.name' ?Like in previous exercises when we want to access a property we used objectName.property??


#4

p is the function parameter, it holds the argument (bob) you passed into the function when calling the function. So yes, they are the same. If you don't know how function arguments/parameters works, you might want to find the exercise which explains this


#5

Thanks a lot :slight_smile: I was a bit confused about the arguments..but now I am clear with it.