ChromeBrowser
ChromeBrowser

Reputation: 219

When to use 'return' inside a method in Javascript

let calculator = {
  sum() {
    return this.a + this.b;
  },

  mul() {
    return this.a * this.b;
  },

  read() {
    this.a = +prompt('a?', 0);
    this.b = +prompt('b?', 0);
  }
};

calculator.read();
alert(calculator.sum());
alert(calculator.mul());

So I've been looking at Javascript codes and if you look at the method

read() {
  this.a = +prompt('a?', 0);
  this.b = +prompt('b?', 0);
}

the read method doesn't return anything to this unlike the sum, mul methods. I am guessing this is because the '=' operator already returns the this.a and this.b to the object. Am I on the right track here?

Upvotes: 0

Views: 54

Answers (1)

Marcus Parsons
Marcus Parsons

Reputation: 1803

First, you're calling .read() which is assigning a value to the a and b properties of the newly created calculator object. It doesn't need to return anything with the way you're using it, because the assignment happens within the function due to the prompt command. Then, when you call .sum() and .mul(), it is using the new property values inside calculator to return a value to the alert function.

Basically, use a return when you need to fill a command with the result of another command; otherwise, you can use assignment like you did here.

Upvotes: 3

Related Questions