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 trialYohanan Braun-Feder
6,101 Pointsconsole 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.
Yohanan Braun-Feder
6,101 PointsTony Nguyen I'm using firefox 38.0.5 on Mac OS X 10.9.5
2 Answers
Matt West
14,545 PointsHi 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
6,101 PointsHi 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
24,934 PointsDid you get the same result on Chrome?
arajay
4,463 Pointscalculator.equals() returns undefined in firefox, but returns the value correctly in chrome
Dylan Macnab
24,861 PointsI 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.
Anthony c
20,907 PointsSame here.
Tony Nguyen
24,934 PointsTony Nguyen
24,934 PointsYour code looks correct. Which browser are you using?