1

I have tried it but it does not return 210

function katatau() {
const oneToTwenty = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
let newArray = 0
for (let i = 0; i <= oneToTwenty.length; i++) {
    newArray += oneToTwenty[i]
} return newArray

}

2
  • use < not <= because arrays start at index [0] - e.g. if you only have one value in an array, it's at index 0, and the length is 1 ... so, array[1] would be undefined Commented Jul 15, 2021 at 1:49
  • It works! Thank you too much! Commented Jul 15, 2021 at 1:56

5 Answers 5

1

One liner using Array.reduce():

const oneToTwenty = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
const sum = oneToTwenty.reduce((a, b) => a + b, 0);
console.log(sum);

Sign up to request clarification or add additional context in comments.

Comments

0

You need to put < sign in for loop instead of <= because the array start with 0 so the last index will be 19 in you term, so using <= will make it go to index 20 which makes it go more than wanted so.

function katatau() {
    const oneToTwenty = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
    let newArray = 0
    for (let i = 0; i <= oneToTwenty.length; i++) {
        newArray += oneToTwenty[i]
    }
    return newArray
}

Comments

0

function to add number in an array:

const addNumber=(arr)=>{
    let sum=0;
        for(let i=0; i<arr.length; i++){
        sum= sum+arr[i];
        }
   console.log(sum);
    return sum;
}

Comments

0

you have very minor issues in code. try this

function katatau() {
            const oneToTwenty = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

            let sumOfArray = 0
      
            //here you used <= which is wrong.
            for (let i = 0; i < oneToTwenty.length; i++) { 
                sumOfArray += oneToTwenty[i]
            }

            console.log(sumOfArray);
            return sumOfArray ;
        }

Comments

0
function katatau() {
    const oneToTwenty = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
    let sum = 0;
    for (let item of oneToTwenty) {
        sum += item;
    }
    return sum
}

console.log(katatau())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.