I'm a beginner in JavaScript and doing an online test to improve my skills. I came across to this question:
So if I am given this array as an example: ([1,2,3,4,5]) the output should be 13
This is what I have got so far:
export function find_total( my_numbers ) {
for(let i = 0; i < my_numbers.length; i++){
if(my_numbers[i] % 2 === 0) {
total = total + 1
}
if(my_numbers[i] % 2 === 1) {
total = total + 3
}
if(my_numbers[i] === 5) {
total = total + 5
}
return total
}
console.log(total)
}
But it is giving me errors. I get the logic in English but couldn't put it in JS. What would be the right syntax here?
The problem is with your if statements.
function find_total( my_numbers ) {
let total = 0;
for(let i = 0; i < my_numbers.length; i++){
if(my_numbers[i] === 5) {
total = total + 5
}
else if(my_numbers[i] % 2 === 0) {
total = total + 1
}
else if(my_numbers[i] % 2 === 1) {
total = total + 3
}
}
return total;
}
console.log(find_total([1,2,3,4,5]))
This code should print the correct result of 13. You were not getting an answer of 13 because 5 is odd so has 3 point and 5 point exclusive to 5. The key is not to treat 5 as having point of odd number but having it's own point irrespective of either it is odd or even.
There are following issues in your code:
total in the function find_total is never initializedreturn statement is misplaced inside the for loop, it must be outside, signifying return value of the function find_totalconsole.log the value of the function, instead of logging it inside. eg. console.log(find_total(...))Fixing these, you will indeed get the return value as 16 for input [1, 2, 3, 4, 5] as pointed out in the comments.
function find_total(my_numbers) {
let total = 0 // Initialize total with a value of 0
for (let i = 0; i < my_numbers.length; i++) {
if (my_numbers[i] % 2 === 0) {
total = total + 1
}
if (my_numbers[i] % 2 === 1) {
total = total + 3
}
if (my_numbers[i] === 5) {
total = total + 5
}
}
return total // return outside the loop
}
console.log(find_total([1, 2, 3, 4, 5])) // console.log outside