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 Modifying Objects with Methods

Trying to store values from the calculator object into an array but...I don't quite have it.

It's all in the console. It looks to me like I should be able to store calculator.equals() by pushing it into calculatorArray. But when I run calculatorArray in the console I get 0. Any thoughts?

var calculator = {
    sum: 0,
    add: function(value){
      this.sum += value;
    },
    clear: function(){
      this.sum = 0;
    },
    equals: function(){
      return this.sum;
    }
}


var calculatorArray = [];
calculatorArray.push(calculator.equals())

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! But sum is zero. And that's what's being pushed to the array :smiley: You haven't used add to add anything to the original sum value which is equal to 0. I've added a few lines of code to yours so you can see more clearly what's going on. Take a look:

var calculator = {
    sum: 0,
    add: function(value){
      this.sum += value;
    },
    clear: function(){
      this.sum = 0;
    },
    equals: function(){
      return this.sum;
    }
}

calculator.add(2);
calculator.add(7);
var calculatorArray = [];
calculatorArray.push(calculator.equals());
console.log(calculatorArray[0]);

Hope this helps! :sparkles:

I haven't tried it yet, but looking at this i realized: the lines that you added, I have been running this in the console. Therefore, I probably should have run the calculatorArray.push(calculator.equals()) in the console as well. Now I'll go try it. Thanks.

Tommaso Poletti
Tommaso Poletti
5,205 Points

I think i understand your problem :) The problem is if u put the ".push" method away from the function inside an object the code run one time and that array doesn't update.

so... if u write

var calculatorArray = [];
var calculator = {
    sum: 0,
    add: function(value){
      calculatorArray.push(value);
      this.sum += value;
    },
    clear: function(){
      this.sum = 0;
    },
    equals: function(){
      console.log(calculatorArray);
      return this.sum;
    }
}

When you add a number to the sum the ".push" method add in the array the number you want

and if u check with calculator.equals the function log in the console the array and the total :)