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

Mikhailo Rozumovskyy
Mikhailo Rozumovskyy
3,779 Points

Why do I recieve [object Object] answer in my CALCULATOR?

I just finished Object Oriented Java Script and trying to put it all together; What should I change? this is my code (it is from one exercise):

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

calculator.add(5);
calculator.equals();
var display = calculator
alert(calculator); 

2 Answers

Hi,

Let's write the code again and see why you're getting that message and what's the solution:

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

Above code is simply a calculator object with a bunch of useful methods.

Now let's analyze your code :

calculator.add(5); //This adds 5 to the sum , so after this sum will be 10.
calculator.equals(); //This returns the sum, but you didn't catch it in a variable
var display = calculator 
alert(calculator);  //calculator is an object and with this line you're going to see "[Object object]" in alert dialog box

Let's see the solution:

calculator.add(5); //This adds 5 to the sum , so after this sum will be 10.
var display = calculator.equals(); //equals() method returns sum "10"and we catch it in a variable called display.
alert(display);  //This will now show value of display variable "10" in an alert dialog box.

I hope it answers your question, Happy Coding !

  • Zain
Mikhailo Rozumovskyy
Mikhailo Rozumovskyy
3,779 Points

ooh, I see, I understand it now. My bad! Thank You!