Lets start with some formatting so we can understand the code:
function sumFibs(num) {
let arr = [];
for (let i = 1; i <= num; i += i) {
arr.push(i);
}
for (let j = 2; j <= arr.length; j += 2) {
arr.splice(j);
}
(arr) => {
return arr.reduce((total, current) => {
return total + current;
}, 0);
}
return arr;
}
sumFibs(4)
Can you explain what this code is supposed to do? Not what the literal syntax means, but why?
Side note - if you aren’t sure exactly how to use fancy syntax, you can stick to only for loops, while loops, and if statements. That will solve 99% of the challenges without any splice or reduce.
The first for loop is meant to loop in the Fibonacci sequence of all integers before and including ‘num’, by adding i to its self. I then put them into an array. The second for loop is meant to loop through all the even numbers before and including num, so that then I could remove them from the array by using splice. Then the reduce function is meant to find the sum of all the numbers in the array, and return it.
The first loop isn’t generating any Fibonacci numbers. It’s making every single integer.
Splice still creates confusing results so it shouldn’t be used in a loop. Also, you aren’t splicing out every other number. Also, it isn’t the case that every other Fibonacci number is even.