0

I have a question about return & console.log. I don't know why their results are different. Who can answer this question? I want to understand them.

// #1
var myObjectA = {
  name: 'Lara',
  getName: function() {
    console.log(this.name);
  }
}
console.log(myObjectA.getName());

// #2
var myObjectB = {
  name: 'Lara',
  getName: function() {
    return this.name
  }
}
console.log(myObjectB.getName());
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Vnfuture
  • 11
  • 1

1 Answers1

1

If you do not return a value from the function, the function call is automatically undefined since there is no value given back to the call.

// #1
var myObjectA = {
  name: 'Lara',
  getName: function() {
    // this is the first Lara we see
    console.log("Within fucntion: " + this.name);
    // this returns the value out to the function call
    return this.name
  }
}
//this function call gets the value we returned inside the function
console.log("The function call: " + myObjectA.getName());

// #2
var myObjectB = {
  name: 'Lara',
  getName: function() {
    return this.name
  }
}
console.log(myObjectB.getName());

If you add a return statement to the first function you can see that the first console.log(myObjectB.getName()); is no longer undefined but you still have the first output from the console.log(this.name) within the function.

Mellik
  • 235
  • 1
  • 9
  • I entered it wrong. Please watch back. – Vnfuture Nov 21 '22 at 11:48
  • 1
    The first Function does not return a value so the first `console.log(myObject.getName());` is undefined. You can see "Lara" in the output field because you are console logging the name within the function. Hope this clears it up. – Mellik Nov 21 '22 at 11:52