Console.log and return are used at the same time?


#1

(Getters and Setters III) lesson

get seatingCapacity() {
console.log(There are ${this._seatingCapacity} seats at Italian Bistro.);
return this._seatingCapacity;
}
}

since it has console.log ,why it needs “return” at the same time ?
many programme used either console.log or return ,why it used at the same time here ?
maybe it is repeated ?
i donot understand this .

thanks


#2

console.log() logs something to the console, a message for the end user of our program.

return means the function/method returns something, hands something back. This is very useful if we still need the result of the function/method later. So its perfectly fine to have both.


#3

for the getter and setter method
the console.log and return are forbidden to use at the same time ?


#4

if something was forbidden, JS would throw us an error.

We can perfectly use these two together. Lets reverse the question, why would it be forbidden to use both console.log and return?


#5

ok ,let us reverse the question ,why it is used the console.log and return both
look at the code below ,why ?
the code :return this._age
it is ussful there for this return ?

let person = {
  _name: 'Lu Xun',
  _age: 137,
  
  set age(ageIn) {
    if (typeof ageIn === 'number') {
      this._age = ageIn;
    }
    else {
      console.log('Invalid input');
      return 'Invalid input';
    }
  },
  
  get age() {
    console.log(`${this._name} is ${this._age} years old.`);
    return this._age;
  }

};


person.age = 'Thirty-nine';
person.age = 39;


console.log(person.age);

#6

if i reverse the question in an attempt to understand why you are struggling, you can’t reverse the question back without answering. I can’t explain something if i don’t understand the struggle

why are you struggling when a method uses both console.log and return? Why isn’t this logic for you?

get age() is a getter function, it retrieves a property (age) of object. By returning the age, we can log the age at method call, or we could capture the age, in case we need this for further usage.

this method has a double roll, both logging to console (to inform the end user), and returning (returned data is useful for our program, if we want to do more with the data). Its coded very defensive, what if later we need the age after calling the method? To be sure, lets return the age.


#8

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