Sum Function with array argument

Multi tool use


Sum Function with array argument
i'm starting studying javascript. I'm stuck with this exercise: Create a function that takes an array as argument and return the sum of all elements of the array.
I have written this code:
function sum(table) {
let x = table[0];
let y = [table.length - 1];
let totale = 0;
for (count = x; count <= y; count++) {
total += x;
x += 1;
};
return total;
};
console.log(sum[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
I don't know why the result is undefined instead of 55. Thanks for helping.
let y = [table.length - 1];
y
Your variable is called
totale
, not total
. And you want to iterate from 0
, not from table[0]
.– Xufox
13 mins ago
totale
total
0
table[0]
2 Answers
2
total
totale
sum([…])
y = table.length - 1
x = 0
total += table[count];
function sum(table) {
let x = 0;
let y = table.length - 1;
let total = 0;
for (count = x; count <= y; count++) {
total += table[count];
};
return total;
};
console.log(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
function sum(table) {
return table.reduce((p,c)=>p+c,0);
};
console.log(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
Yeah, definitely not what I would do for a sum, but hopefully this will get him started. He's new and just needs a guiding hand
– vol7ron
7 mins ago
reduce
ftw imo– stwilz
1 min ago
reduce
Here are couple of things.
You need to execute the sum function by calling like sum([array elements])
.Note the (
& )
braces
Secondly count <= y
will give undefined as it will exceed the length of the array. The array index starts from 0;
sum([array elements])
(
)
count <= y
There is a typo here totale
.
totale
You can avoid these set of lines
let x = table[0];
let y = [table.length - 1];
if you just initialize the loop conditional statement like this
for (let count = 0; count < table.length; count++)
function sum(table) {
let x = 0
for (let count = 0; count < table.length; count++) {
x += table[count];
};
return x;
};
console.log(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
let y = [table.length - 1];
I don't think you wanty
to be an array.– CertainPerformance
13 mins ago