0

I am trying to solve 3 questions and am not sure what I am doing wrong.

1.I'm supposed to loop to see if elements in var arr are numbers 2.then im supposed to find if the numbers are even 3.then keep track of the even numbers by increasing the value of count Here is my code:

    var arr = ["100", 33, "Hello"]

    function isEven(arr) {
    var count = 0
    arr.forEach(function(element){
    if(typeof element === "number") {
    if(typeof element % 2 =0) {
    }
    }
    })
    return count
    }
    isEven(arr)
6Ortiz
  • 39
  • 1
  • 1
  • 7
  • The main problem above is that you're using `= 0` instead of `== 0` or `=== 0` to compare; see the linked question's answers. You're also using `typeof` in the second `if`, but you've already checked the type. Now you just want to do the calculation. Finally, you don't increase `count` anywhere. So remove `typeof` from the line with the `%`, and add `++count;` inside that `if` statement's body (and fix the `=` / `==` or `===` thing). :-) Note also that you can combine conditions in a single `if` with `&&`. – T.J. Crowder Aug 27 '18 at 13:29

1 Answers1

1

You can use the typeof operator to check if a variable is of type number. To check if a number is even, check if its remainder is 0 after dividing it by 2.

function isEven(arr){
    var count = 0;
    arr.forEach(function(element){
    if(typeof element === "number" && element % 2 == 0){
        count++;
       }
    }
}
Aayush Sharma
  • 779
  • 4
  • 20
full-stack
  • 553
  • 5
  • 20