Search code examples
javascriptarraysfor-loopecmascript-6multiplication

Javascript - How to return the correct value with the multiplication of all the elements of an array?


What I'm trying to do here it's multiply all the elements of the array A. With these values: [1,2,0,-5]it should returns 0... but it returns 1. What I'm doing wrong? Here's the code:

function solution(A){
    let multi = 1;
    for(i = 1; i < A.length; i++){
        multi *= A[i]
    } 

    if(multi = 30){
        return 1
    } else if (multi = -30){
        return -1
    } else if (multi = 0){
        return 0
    } else{
        console.log("hey hey");
    }
}

solution(A = [1,2,0,-5])

Solution

  • Your loop is starting at 1 - JavaScript arrays (and arrays in many other languages) are 0-indexed, so start at 0. Your if conditions are also wrong - use the comparison operator == not the assignment operator =.

    function solution(A){
        let multi = 1;
        for(i = 0; i < A.length; i++){
            multi *= A[i]
        } 
    
        if(multi == 30){
            return 1
        } else if (multi == -30){
            return -1
        } else if (multi == 0){
            return 0
        } else{
            console.log("hey hey");
        }
    }