0

below is a simple function. It's adds all number in the array and store in a variable. The problem is, the loop execute just once even though the condition for exiting the loop was not met. Am I missing something here?

const numChecker = (...args) => {
  let x = args;
  let y;
  let i;
    for (i = 0; i < x.length - 1; i++) {
      if ((typeof x[i]) === "number") {
      y += x[i];
      }
      return y;
    }
 }

console.log(numChecker("A", "B", "C", 100, 300, 200));

2
  • 1
    Because of i < x.length - 1?? Commented Oct 4, 2018 at 3:29
  • you are using return inside the loop ... that returns out of your function ... so of course it only runs once Commented Oct 4, 2018 at 3:33

1 Answer 1

1

There are 3 issues with your code :-

  1. First is let y;.
  2. Second is i < x.length - 1.
  3. You're doing return y at wrong place.

In the first issue, when you declare a variable like this let y, then the typeof(y) is undefined. Here, you want to store the sum of numbers, so the variable y must be of type number. So, you must declare and initialize it like let y = 0;

In 2nd one, in the loop, the array will be parsed to 2nd last element. x[4] in your case. So, the condition in the loop should be like i < x.length.

In the last, you must return y outside the loop, so that the sum will be printed on the console will be of all the numbers in the array.

Check the Snippet below.

const numChecker = (...args) => {
  let x = args;
  let y = 0;
  let i;
  for (i = 0; i < x.length; i++) {
    if ((typeof x[i]) === "number") {
      y += x[i];
    }
  }
  return y;
}

console.log(numChecker("A", "B", "C", 100, 300, 200));

Hope, it will solve your issue.

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

1 Comment

Welcome, @AldrinEspinosa

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.