Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Incorrect output while summing even numbers in an array in JavaScript

I am trying to implement a function that takes an array of numbers as input and returns the sum of all the even numbers in the array efficiently.

This code works fine for some inputs, but for certain inputs like [1,2,3,4,5,6], it returns 12, which is incorrect. I’ve been trying to figure out the issue for hours but can’t seem to find the solution. Can someone help me figure out what’s going wrong here and how to fix it? Thank you in advance.

My code looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function sumEvenNumbers(arr) {
  let result = 0;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] % 2 === 0) {
      result += arr[i];
    }
  }
  return result;
}

console.log(sumEvenNumbers([1, 2, 3, 4, 5, 6]));

>Solution :

The code seems to be working fine, it sums all the even numbers in the input array. The issue could be with the input data. The code only checks if the number is divisible by 2 and adds it to the result, it does not check if the input is actually a number. To fix this issue, you can add a check before performing the calculation to make sure the input is a number. Here’s an updated version of the code:

function sumEvenNumbers(arr) {
  let result = 0;
  for (let i = 0; i < arr.length; i++) {
    if (typeof arr[i] === 'number' && arr[i] % 2 === 0) {
      result += arr[i];
    }
  }
  return result;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading