Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • Array Addition Doesn't Run Correctly - JavaScript
    Hello everyone, I want to ask why the following code doesn't return the largest number in the array? When I break the code down into it's simpler components it all works fine. However, when I put it together, it gives me the wrong answer. Any insight would be appreciated. Thank you.
    function ArrayAdditionI(arr) { 
        var largest = 0;
        for(var i = 0; i < arr.length; i++){
            if(arr[i] > largest){
                largest = arr[i];
            }
        }
        return largest
    }
    //console.log(ArrayAdditionI(1,2,3,5)):
    //returns 0 instead of 5
    
    gusmanbhai posted this question on 7/15/16 | array, addition, javascript
    Answers
  • +
  • 2
  • -
  • this code does work. you are not passing the function an array. You are passing in several parameters.
    console.log( ArrayAddition( [1,2,3,4,5] )
    
    when you do this
    console.log( ArrayAddition( 1,2,3,4,5 )
    
    the function takes the first parameter 1 and uses that number as your arr variable. Thus returning 0 because numbers have no length, the loop does not trigger. Javascript functions don't have a fixed parameter list. So you can pass in as many as you like.
    someFunction( param1, param2, param3, param4, param5 .....paramN )
    
    Log in to write an answer.