educative.io

Educative

Doubling array elements

Can someone please explain to me why my code below is not passing? The reason it gives is “Must return an array”. It is though, isn’t it?

function double(arr) {
for (let i=0; i<0; i++) {
let arr2 = [];
arr2.push(arr[i] * 2);
return arr2;
}
}
let arr1 = [1, 2, 3];
let arrDouble = double(arr1);


Type your question above this line.

Course: https://www.educative.io/collection/5679346740101120/5720605454237696
Lesson: https://www.educative.io/collection/page/5679346740101120/5720605454237696/5647906690301952

Hello @Lepros

Your code is not passing because the for loop will not execute at all. This is because i=0 and i<0 are the conditions you are providing to it hence this loop will be skipped altogether and only the last two lines will be executed. Nothing will be returned from the function and hence the error Must return an array. Also you have to define arr2 outside the for loop and not inside it. Finally return statement should also be outside the loop. Following is the correct implementation of your code:

function double(arr) {
    let newArr = [];
    for(let i = 0; i < arr.length; i++){
        newArr.push(arr[i] * 2);
    }
    return newArr;
}

Hope this helps!

1 Like

Thank you so much! I really appreciate the explanation as well. Very helpful!