Eloquent Javascript: The sum of an array
I want a sum function that takes an array of numbers and returns the sum of these numbers.
I wrote the following, but it always returns undefined
:
function sum(array){
var sumVar;
for(i = 0; i <= array[array.length]; i++){
sumVar += array[i];
}
return sumVar;
}
console.log(sum([1,2,3]));
// → undefined
Could anyone help explain why this is happening? I'm not so much concerned with the solution as I am with what I'm doing wrong.
javascript arrays
add a comment |
I want a sum function that takes an array of numbers and returns the sum of these numbers.
I wrote the following, but it always returns undefined
:
function sum(array){
var sumVar;
for(i = 0; i <= array[array.length]; i++){
sumVar += array[i];
}
return sumVar;
}
console.log(sum([1,2,3]));
// → undefined
Could anyone help explain why this is happening? I'm not so much concerned with the solution as I am with what I'm doing wrong.
javascript arrays
3
an eloquent solution for sum would take advantage ofArray.prototype.reduce
.
– zzzzBov
Jan 12 '15 at 2:35
add a comment |
I want a sum function that takes an array of numbers and returns the sum of these numbers.
I wrote the following, but it always returns undefined
:
function sum(array){
var sumVar;
for(i = 0; i <= array[array.length]; i++){
sumVar += array[i];
}
return sumVar;
}
console.log(sum([1,2,3]));
// → undefined
Could anyone help explain why this is happening? I'm not so much concerned with the solution as I am with what I'm doing wrong.
javascript arrays
I want a sum function that takes an array of numbers and returns the sum of these numbers.
I wrote the following, but it always returns undefined
:
function sum(array){
var sumVar;
for(i = 0; i <= array[array.length]; i++){
sumVar += array[i];
}
return sumVar;
}
console.log(sum([1,2,3]));
// → undefined
Could anyone help explain why this is happening? I'm not so much concerned with the solution as I am with what I'm doing wrong.
javascript arrays
javascript arrays
edited Jan 12 '15 at 2:58
Oriol
155k33260359
155k33260359
asked Jan 12 '15 at 2:20
sshafer15
61
61
3
an eloquent solution for sum would take advantage ofArray.prototype.reduce
.
– zzzzBov
Jan 12 '15 at 2:35
add a comment |
3
an eloquent solution for sum would take advantage ofArray.prototype.reduce
.
– zzzzBov
Jan 12 '15 at 2:35
3
3
an eloquent solution for sum would take advantage of
Array.prototype.reduce
.– zzzzBov
Jan 12 '15 at 2:35
an eloquent solution for sum would take advantage of
Array.prototype.reduce
.– zzzzBov
Jan 12 '15 at 2:35
add a comment |
4 Answers
4
active
oldest
votes
While there are multiple areas of your code which seems incorrect (as addressed by @meagar), the reason why you still get undefined
after changing your loop iteration to stop at array.length
is because you didn't initialize sumVar
to 0.
function sum (array) {
var sumVar = 0;
for(var i = 0; i < array.length; i += 1) {
sumVar += array[i];
}
return sumVar;
}
sum( [1, 2] ); // results in 3
Thanks, that fixed it. Why do I need to initialize sumVar to zero?
– sshafer15
Jan 12 '15 at 2:37
2
You need to initialize sumVar to 0 because initially it's value isundefined
. When you try to add numbers toundefined
, what you'll end up with is the valueNaN
.
– wmock
Jan 12 '15 at 2:39
add a comment |
Your condition, i <= array[array.length]
, makes no sense.
You're looping while i
is less than array[array.length]
, which is one-past the last element of the array. This will typically be undefined
. i <= undefined
is always false, and obviously isn't what you want.
If you want to iterate over each element of the array, i
is the index and you need to loop from 0 to one less than array.length
. Your condition should be i < array.length
.
When I try this I get Not a Number. Any ideas why?
– sshafer15
Jan 12 '15 at 2:28
2
Small nitpick: The end condition of the for loop should bei < array.length
since JavaScript uses zero-based array indexing.
– Platinum Azure
Jan 12 '15 at 2:29
add a comment |
As @zzzzBov hinted in a comment, there is a more eloquent solution than the imperative loop, a solution involving some functional techniques:
var add = function(a, b) {return a + b;};
var sum = function(nums) {return nums.reduce(add, 0);};
In a library like Ramda, where functions like reduce
are curried and the list parameter comes last, this would be even easier (although redundant, since Ramda already includes sum
):
var sum = R.reduce(add, 0);
Any comment to go with the downvote?
– Scott Sauyet
Jan 12 '15 at 19:01
I have just found out about Ramda today! How long has it been around? 2 years? BTW Isn't your R.reduce() missing the array param? It is nice we can now do R.sum([1,2,3,4,5]) without writing your sum function. We can code JS like Python with Ramda.
– yoshi
Nov 9 '16 at 13:20
Ramda's about 3 years old. But the first public announcement was in May, 2014. Not having the array parameter is very much intentional. If you want to see a long contentious discussion about the reason for it, there's one at github.com/ramda/ramda/issues/452. I don't think of it much like Python. More like Haskell, LISP, ML, F#, OCaml and other FP languages.
– Scott Sauyet
Nov 11 '16 at 2:47
Oh ok you did it intentionally. Sorry.
– yoshi
Nov 15 '16 at 12:13
add a comment |
You can try this:
function sumOfArray(array) {
return eval(array.join('+'));
}
console.log(sumOfArray([4,4])); // result 4+4 = 8
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f27894484%2feloquent-javascript-the-sum-of-an-array%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
While there are multiple areas of your code which seems incorrect (as addressed by @meagar), the reason why you still get undefined
after changing your loop iteration to stop at array.length
is because you didn't initialize sumVar
to 0.
function sum (array) {
var sumVar = 0;
for(var i = 0; i < array.length; i += 1) {
sumVar += array[i];
}
return sumVar;
}
sum( [1, 2] ); // results in 3
Thanks, that fixed it. Why do I need to initialize sumVar to zero?
– sshafer15
Jan 12 '15 at 2:37
2
You need to initialize sumVar to 0 because initially it's value isundefined
. When you try to add numbers toundefined
, what you'll end up with is the valueNaN
.
– wmock
Jan 12 '15 at 2:39
add a comment |
While there are multiple areas of your code which seems incorrect (as addressed by @meagar), the reason why you still get undefined
after changing your loop iteration to stop at array.length
is because you didn't initialize sumVar
to 0.
function sum (array) {
var sumVar = 0;
for(var i = 0; i < array.length; i += 1) {
sumVar += array[i];
}
return sumVar;
}
sum( [1, 2] ); // results in 3
Thanks, that fixed it. Why do I need to initialize sumVar to zero?
– sshafer15
Jan 12 '15 at 2:37
2
You need to initialize sumVar to 0 because initially it's value isundefined
. When you try to add numbers toundefined
, what you'll end up with is the valueNaN
.
– wmock
Jan 12 '15 at 2:39
add a comment |
While there are multiple areas of your code which seems incorrect (as addressed by @meagar), the reason why you still get undefined
after changing your loop iteration to stop at array.length
is because you didn't initialize sumVar
to 0.
function sum (array) {
var sumVar = 0;
for(var i = 0; i < array.length; i += 1) {
sumVar += array[i];
}
return sumVar;
}
sum( [1, 2] ); // results in 3
While there are multiple areas of your code which seems incorrect (as addressed by @meagar), the reason why you still get undefined
after changing your loop iteration to stop at array.length
is because you didn't initialize sumVar
to 0.
function sum (array) {
var sumVar = 0;
for(var i = 0; i < array.length; i += 1) {
sumVar += array[i];
}
return sumVar;
}
sum( [1, 2] ); // results in 3
answered Jan 12 '15 at 2:33
wmock
2,92322652
2,92322652
Thanks, that fixed it. Why do I need to initialize sumVar to zero?
– sshafer15
Jan 12 '15 at 2:37
2
You need to initialize sumVar to 0 because initially it's value isundefined
. When you try to add numbers toundefined
, what you'll end up with is the valueNaN
.
– wmock
Jan 12 '15 at 2:39
add a comment |
Thanks, that fixed it. Why do I need to initialize sumVar to zero?
– sshafer15
Jan 12 '15 at 2:37
2
You need to initialize sumVar to 0 because initially it's value isundefined
. When you try to add numbers toundefined
, what you'll end up with is the valueNaN
.
– wmock
Jan 12 '15 at 2:39
Thanks, that fixed it. Why do I need to initialize sumVar to zero?
– sshafer15
Jan 12 '15 at 2:37
Thanks, that fixed it. Why do I need to initialize sumVar to zero?
– sshafer15
Jan 12 '15 at 2:37
2
2
You need to initialize sumVar to 0 because initially it's value is
undefined
. When you try to add numbers to undefined
, what you'll end up with is the value NaN
.– wmock
Jan 12 '15 at 2:39
You need to initialize sumVar to 0 because initially it's value is
undefined
. When you try to add numbers to undefined
, what you'll end up with is the value NaN
.– wmock
Jan 12 '15 at 2:39
add a comment |
Your condition, i <= array[array.length]
, makes no sense.
You're looping while i
is less than array[array.length]
, which is one-past the last element of the array. This will typically be undefined
. i <= undefined
is always false, and obviously isn't what you want.
If you want to iterate over each element of the array, i
is the index and you need to loop from 0 to one less than array.length
. Your condition should be i < array.length
.
When I try this I get Not a Number. Any ideas why?
– sshafer15
Jan 12 '15 at 2:28
2
Small nitpick: The end condition of the for loop should bei < array.length
since JavaScript uses zero-based array indexing.
– Platinum Azure
Jan 12 '15 at 2:29
add a comment |
Your condition, i <= array[array.length]
, makes no sense.
You're looping while i
is less than array[array.length]
, which is one-past the last element of the array. This will typically be undefined
. i <= undefined
is always false, and obviously isn't what you want.
If you want to iterate over each element of the array, i
is the index and you need to loop from 0 to one less than array.length
. Your condition should be i < array.length
.
When I try this I get Not a Number. Any ideas why?
– sshafer15
Jan 12 '15 at 2:28
2
Small nitpick: The end condition of the for loop should bei < array.length
since JavaScript uses zero-based array indexing.
– Platinum Azure
Jan 12 '15 at 2:29
add a comment |
Your condition, i <= array[array.length]
, makes no sense.
You're looping while i
is less than array[array.length]
, which is one-past the last element of the array. This will typically be undefined
. i <= undefined
is always false, and obviously isn't what you want.
If you want to iterate over each element of the array, i
is the index and you need to loop from 0 to one less than array.length
. Your condition should be i < array.length
.
Your condition, i <= array[array.length]
, makes no sense.
You're looping while i
is less than array[array.length]
, which is one-past the last element of the array. This will typically be undefined
. i <= undefined
is always false, and obviously isn't what you want.
If you want to iterate over each element of the array, i
is the index and you need to loop from 0 to one less than array.length
. Your condition should be i < array.length
.
edited Jan 12 '15 at 2:33
answered Jan 12 '15 at 2:22
meagar♦
177k29272288
177k29272288
When I try this I get Not a Number. Any ideas why?
– sshafer15
Jan 12 '15 at 2:28
2
Small nitpick: The end condition of the for loop should bei < array.length
since JavaScript uses zero-based array indexing.
– Platinum Azure
Jan 12 '15 at 2:29
add a comment |
When I try this I get Not a Number. Any ideas why?
– sshafer15
Jan 12 '15 at 2:28
2
Small nitpick: The end condition of the for loop should bei < array.length
since JavaScript uses zero-based array indexing.
– Platinum Azure
Jan 12 '15 at 2:29
When I try this I get Not a Number. Any ideas why?
– sshafer15
Jan 12 '15 at 2:28
When I try this I get Not a Number. Any ideas why?
– sshafer15
Jan 12 '15 at 2:28
2
2
Small nitpick: The end condition of the for loop should be
i < array.length
since JavaScript uses zero-based array indexing.– Platinum Azure
Jan 12 '15 at 2:29
Small nitpick: The end condition of the for loop should be
i < array.length
since JavaScript uses zero-based array indexing.– Platinum Azure
Jan 12 '15 at 2:29
add a comment |
As @zzzzBov hinted in a comment, there is a more eloquent solution than the imperative loop, a solution involving some functional techniques:
var add = function(a, b) {return a + b;};
var sum = function(nums) {return nums.reduce(add, 0);};
In a library like Ramda, where functions like reduce
are curried and the list parameter comes last, this would be even easier (although redundant, since Ramda already includes sum
):
var sum = R.reduce(add, 0);
Any comment to go with the downvote?
– Scott Sauyet
Jan 12 '15 at 19:01
I have just found out about Ramda today! How long has it been around? 2 years? BTW Isn't your R.reduce() missing the array param? It is nice we can now do R.sum([1,2,3,4,5]) without writing your sum function. We can code JS like Python with Ramda.
– yoshi
Nov 9 '16 at 13:20
Ramda's about 3 years old. But the first public announcement was in May, 2014. Not having the array parameter is very much intentional. If you want to see a long contentious discussion about the reason for it, there's one at github.com/ramda/ramda/issues/452. I don't think of it much like Python. More like Haskell, LISP, ML, F#, OCaml and other FP languages.
– Scott Sauyet
Nov 11 '16 at 2:47
Oh ok you did it intentionally. Sorry.
– yoshi
Nov 15 '16 at 12:13
add a comment |
As @zzzzBov hinted in a comment, there is a more eloquent solution than the imperative loop, a solution involving some functional techniques:
var add = function(a, b) {return a + b;};
var sum = function(nums) {return nums.reduce(add, 0);};
In a library like Ramda, where functions like reduce
are curried and the list parameter comes last, this would be even easier (although redundant, since Ramda already includes sum
):
var sum = R.reduce(add, 0);
Any comment to go with the downvote?
– Scott Sauyet
Jan 12 '15 at 19:01
I have just found out about Ramda today! How long has it been around? 2 years? BTW Isn't your R.reduce() missing the array param? It is nice we can now do R.sum([1,2,3,4,5]) without writing your sum function. We can code JS like Python with Ramda.
– yoshi
Nov 9 '16 at 13:20
Ramda's about 3 years old. But the first public announcement was in May, 2014. Not having the array parameter is very much intentional. If you want to see a long contentious discussion about the reason for it, there's one at github.com/ramda/ramda/issues/452. I don't think of it much like Python. More like Haskell, LISP, ML, F#, OCaml and other FP languages.
– Scott Sauyet
Nov 11 '16 at 2:47
Oh ok you did it intentionally. Sorry.
– yoshi
Nov 15 '16 at 12:13
add a comment |
As @zzzzBov hinted in a comment, there is a more eloquent solution than the imperative loop, a solution involving some functional techniques:
var add = function(a, b) {return a + b;};
var sum = function(nums) {return nums.reduce(add, 0);};
In a library like Ramda, where functions like reduce
are curried and the list parameter comes last, this would be even easier (although redundant, since Ramda already includes sum
):
var sum = R.reduce(add, 0);
As @zzzzBov hinted in a comment, there is a more eloquent solution than the imperative loop, a solution involving some functional techniques:
var add = function(a, b) {return a + b;};
var sum = function(nums) {return nums.reduce(add, 0);};
In a library like Ramda, where functions like reduce
are curried and the list parameter comes last, this would be even easier (although redundant, since Ramda already includes sum
):
var sum = R.reduce(add, 0);
edited May 23 '17 at 10:30
Community♦
11
11
answered Jan 12 '15 at 4:39
Scott Sauyet
19.7k22653
19.7k22653
Any comment to go with the downvote?
– Scott Sauyet
Jan 12 '15 at 19:01
I have just found out about Ramda today! How long has it been around? 2 years? BTW Isn't your R.reduce() missing the array param? It is nice we can now do R.sum([1,2,3,4,5]) without writing your sum function. We can code JS like Python with Ramda.
– yoshi
Nov 9 '16 at 13:20
Ramda's about 3 years old. But the first public announcement was in May, 2014. Not having the array parameter is very much intentional. If you want to see a long contentious discussion about the reason for it, there's one at github.com/ramda/ramda/issues/452. I don't think of it much like Python. More like Haskell, LISP, ML, F#, OCaml and other FP languages.
– Scott Sauyet
Nov 11 '16 at 2:47
Oh ok you did it intentionally. Sorry.
– yoshi
Nov 15 '16 at 12:13
add a comment |
Any comment to go with the downvote?
– Scott Sauyet
Jan 12 '15 at 19:01
I have just found out about Ramda today! How long has it been around? 2 years? BTW Isn't your R.reduce() missing the array param? It is nice we can now do R.sum([1,2,3,4,5]) without writing your sum function. We can code JS like Python with Ramda.
– yoshi
Nov 9 '16 at 13:20
Ramda's about 3 years old. But the first public announcement was in May, 2014. Not having the array parameter is very much intentional. If you want to see a long contentious discussion about the reason for it, there's one at github.com/ramda/ramda/issues/452. I don't think of it much like Python. More like Haskell, LISP, ML, F#, OCaml and other FP languages.
– Scott Sauyet
Nov 11 '16 at 2:47
Oh ok you did it intentionally. Sorry.
– yoshi
Nov 15 '16 at 12:13
Any comment to go with the downvote?
– Scott Sauyet
Jan 12 '15 at 19:01
Any comment to go with the downvote?
– Scott Sauyet
Jan 12 '15 at 19:01
I have just found out about Ramda today! How long has it been around? 2 years? BTW Isn't your R.reduce() missing the array param? It is nice we can now do R.sum([1,2,3,4,5]) without writing your sum function. We can code JS like Python with Ramda.
– yoshi
Nov 9 '16 at 13:20
I have just found out about Ramda today! How long has it been around? 2 years? BTW Isn't your R.reduce() missing the array param? It is nice we can now do R.sum([1,2,3,4,5]) without writing your sum function. We can code JS like Python with Ramda.
– yoshi
Nov 9 '16 at 13:20
Ramda's about 3 years old. But the first public announcement was in May, 2014. Not having the array parameter is very much intentional. If you want to see a long contentious discussion about the reason for it, there's one at github.com/ramda/ramda/issues/452. I don't think of it much like Python. More like Haskell, LISP, ML, F#, OCaml and other FP languages.
– Scott Sauyet
Nov 11 '16 at 2:47
Ramda's about 3 years old. But the first public announcement was in May, 2014. Not having the array parameter is very much intentional. If you want to see a long contentious discussion about the reason for it, there's one at github.com/ramda/ramda/issues/452. I don't think of it much like Python. More like Haskell, LISP, ML, F#, OCaml and other FP languages.
– Scott Sauyet
Nov 11 '16 at 2:47
Oh ok you did it intentionally. Sorry.
– yoshi
Nov 15 '16 at 12:13
Oh ok you did it intentionally. Sorry.
– yoshi
Nov 15 '16 at 12:13
add a comment |
You can try this:
function sumOfArray(array) {
return eval(array.join('+'));
}
console.log(sumOfArray([4,4])); // result 4+4 = 8
add a comment |
You can try this:
function sumOfArray(array) {
return eval(array.join('+'));
}
console.log(sumOfArray([4,4])); // result 4+4 = 8
add a comment |
You can try this:
function sumOfArray(array) {
return eval(array.join('+'));
}
console.log(sumOfArray([4,4])); // result 4+4 = 8
You can try this:
function sumOfArray(array) {
return eval(array.join('+'));
}
console.log(sumOfArray([4,4])); // result 4+4 = 8
edited Nov 19 '18 at 16:06
DaFois
1,90641418
1,90641418
answered Nov 19 '18 at 15:52
Rahi
14
14
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f27894484%2feloquent-javascript-the-sum-of-an-array%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
3
an eloquent solution for sum would take advantage of
Array.prototype.reduce
.– zzzzBov
Jan 12 '15 at 2:35