Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Object-Oriented JavaScript (2015) Introduction to Methods Finishing the Calculator

Mike Ulvila
Mike Ulvila
16,268 Points

Task 2 of 3: Implement the multiply method.

Will someone please help me with the code for the multiply method. I keep getting errors and can't figure it out. Thanks

Please post the code you have tried so far.

Mike Ulvila
Mike Ulvila
16,268 Points

this is one of many i've tried. i know it's not right because it would be passing the same number as the value. var calculator = { sum: 0, add: function(value) { this.sum += value; }, subtract: function(value) { this.sum -= value; }, multiply: function(value) { this.sum = this.add(value) * value; },

2 Answers

You appear to be making the task more complicated than it needs to be.

Try to keep it simple:

function(value) {
    this.sum *= value
}

You can do the same thing with the '/=' operator as well.

If you want to make it more verbose, you could do:

function(value) {
    this.sum = (this.sum * value)
}
Mike Ulvila
Mike Ulvila
16,268 Points

Ok, thank you, that works. I guess in my mind I was thinking since the sum = 0, no matter what value you put it it's going to return 0 right???

You can't assume the sum will always be equal to 0. It could very well end up holding a running total that will be updated many times. In that case, your original formula could produce incorrect results.

By keeping the multiply function's code very narrow in functionality you end up programming defensively against possible future errors. And that's always a good thing.

I also edited my answer to include another example if you want to see the non-shorthand code.

Mike Ulvila
Mike Ulvila
16,268 Points

Ok, thanks again for your help!

Cosimo Scarpa
Cosimo Scarpa
14,047 Points

The result need to be something like this

var calculator = {
  sum: 0,
  add: function(value) {
    this.sum = (this.sum + value)
  },
  subtract: function(value) {
    this.sum = (this.sum - value)
  },
  multiply: function(value) {
    this.sum = (this.sum * value)
  },
  divide: function(value) {
    this.sum = (this.sum / value)
  },
  clear: function() {
    this.sum = 0;
  }, 
  equals: function() {
    return this.sum;
  }
}