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

Yohanan Braun-Feder
Yohanan Braun-Feder
6,101 Points

console returns "undefined" value with lesson's code. why?

this is the code I wrote in the lesson. it keeps returning an "undefined" value when I try accessing it through the console.

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

for instance i'd write calculator.add(4); calculator.add(3); calculator.equals()

to the console and get "undefined" at the end.

Tony Nguyen
Tony Nguyen
24,934 Points

Your code looks correct. Which browser are you using?

2 Answers

Matt West
Matt West
14,545 Points

Hi Yohanan,

This is happening because the add and clear methods do not return anything. When you execute these methods in the console, undefined is printed to let you know that that the method did not return any data.

Executing the calculator.equals() method will output the value of sum in the console as this function has a return statement.

Yohanan Braun-Feder
Yohanan Braun-Feder
6,101 Points

Hi Matt,

while your answer sounds correct, this is the console input and output from running this program

calculator.add(4); calculator.add(3); calculator.equals()

undefined

Tony Nguyen
Tony Nguyen
24,934 Points

Did you get the same result on Chrome?

calculator.equals() returns undefined in firefox, but returns the value correctly in chrome

Dylan Macnab
Dylan Macnab
24,861 Points

I was having the same issue with the equals method returning undefined while testing my code in Chrome. I tested the same code in Safari and it fixed the issue. Not sure what's happening with that but I figured I'd share for those having a similar problem.