Eloquent Javascript: The sum of an array












0














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.










share|improve this question




















  • 3




    an eloquent solution for sum would take advantage of Array.prototype.reduce.
    – zzzzBov
    Jan 12 '15 at 2:35
















0














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.










share|improve this question




















  • 3




    an eloquent solution for sum would take advantage of Array.prototype.reduce.
    – zzzzBov
    Jan 12 '15 at 2:35














0












0








0







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.










share|improve this question















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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








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 of Array.prototype.reduce.
    – zzzzBov
    Jan 12 '15 at 2:35














  • 3




    an eloquent solution for sum would take advantage of Array.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












4 Answers
4






active

oldest

votes


















0














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





share|improve this answer





















  • 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 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



















0














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.






share|improve this answer























  • 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 be i < array.length since JavaScript uses zero-based array indexing.
    – Platinum Azure
    Jan 12 '15 at 2:29



















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);





share|improve this answer























  • 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



















0














You can try this:



function sumOfArray(array) {
return eval(array.join('+'));
}

console.log(sumOfArray([4,4])); // result 4+4 = 8





share|improve this answer























    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
    });


    }
    });














    draft saved

    draft discarded


















    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









    0














    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





    share|improve this answer





















    • 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 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
















    0














    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





    share|improve this answer





















    • 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 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














    0












    0








    0






    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





    share|improve this answer












    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






    share|improve this answer












    share|improve this answer



    share|improve this answer










    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 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


















    • 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 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
















    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













    0














    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.






    share|improve this answer























    • 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 be i < array.length since JavaScript uses zero-based array indexing.
      – Platinum Azure
      Jan 12 '15 at 2:29
















    0














    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.






    share|improve this answer























    • 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 be i < array.length since JavaScript uses zero-based array indexing.
      – Platinum Azure
      Jan 12 '15 at 2:29














    0












    0








    0






    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.






    share|improve this answer














    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.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    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 be i < 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






    • 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
















    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











    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);





    share|improve this answer























    • 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
















    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);





    share|improve this answer























    • 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














    0












    0








    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);





    share|improve this answer














    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);






    share|improve this answer














    share|improve this answer



    share|improve this answer








    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


















    • 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











    0














    You can try this:



    function sumOfArray(array) {
    return eval(array.join('+'));
    }

    console.log(sumOfArray([4,4])); // result 4+4 = 8





    share|improve this answer




























      0














      You can try this:



      function sumOfArray(array) {
      return eval(array.join('+'));
      }

      console.log(sumOfArray([4,4])); // result 4+4 = 8





      share|improve this answer


























        0












        0








        0






        You can try this:



        function sumOfArray(array) {
        return eval(array.join('+'));
        }

        console.log(sumOfArray([4,4])); // result 4+4 = 8





        share|improve this answer














        You can try this:



        function sumOfArray(array) {
        return eval(array.join('+'));
        }

        console.log(sumOfArray([4,4])); // result 4+4 = 8






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 19 '18 at 16:06









        DaFois

        1,90641418




        1,90641418










        answered Nov 19 '18 at 15:52









        Rahi

        14




        14






























            draft saved

            draft discarded




















































            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.




            draft saved


            draft discarded














            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





















































            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







            Popular posts from this blog

            Can a sorcerer learn a 5th-level spell early by creating spell slots using the Font of Magic feature?

            Does disintegrating a polymorphed enemy still kill it after the 2018 errata?

            A Topological Invariant for $pi_3(U(n))$