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
Jeremy Diallo
3,846 Pointswhat's wrong with my perfect code ?
Hi, I'm following the Eloquent Javascript book along with the Treehouse JavaScript basics course. But I'm stuck with an exercice, and I can't know what I did wrong.
I'm suppose to create two functions sum and range.
range(a,b,c) is suppose to return an array that contains all numbers between a and b, with an optional step of c.
sum(array) takes an array as its argument. It's suppose to return the sum of all the numbers within the array.
Here's my code : (I did it for a positive step first)
function range(start, end, step) {
var array = [];
if (step == null) step = 1;
for (var count = start; count <= end; count+=step)
array.push(count);
return array
}
function sum(array) {
total = 0;
for (var i = 0; i < array.length; i +=1)
console.log(total);
total += array[i];
return total;
}
Here's the result in the console (notice that I printed total to the console to try and get an idea of what was going wrong) :
http://image.noelshack.com/fichiers/2015/36/1441559620-sans-titre.jpg
And here's the solution that works when I run it :
function range(start, end, step) {
if (step == null) step = 1;
var array = [];
if (step > 0) {
for (var i = start; i <= end; i += step)
array.push(i);
} else {
for (var i = start; i >= end; i += step)
array.push(i);
}
return array;
}
function sum(array) {
var total = 0;
for (var i = 0; i < array.length; i++)
total += array[i];
return total;
}
What the hell is going on ? I can't spot any difference...
Thanks for your help !!!
2 Answers
akak
29,446 PointsCheck you curly brackets after if's and for loops in both functions. When I added curly brackets to sum function from the first example it worked. I assume if you'd add them to the first function things will get better as well.
You can add use strict at the beginning of your code and fix errors console will give you. It's good practice to work in strict mode as you know what is happening in your code. No syntax error will go unnoticed ;)
'use strict';
function range(start, end, step) {
var array = [];
Jeremy Diallo
3,846 PointsI just got a similar problem : the function returned some undefined values while the code is perfectly valid...
Jeremy Diallo
3,846 PointsJeremy Diallo
3,846 Pointsthat's what I did, it still doesn't work...