w3resource

JavaScript: Find the number of even digits in a given integer

JavaScript Basic: Exercise-130 with Solution

Write a JavaScript program to find the number of even digits in a given integer.

Pictorial Presentation:

JavaScript: Find the number of even digits in a given integer.

Sample Solution:

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title> Find the number of even digits in a given integer</title>
</head>
<body>

</body>
</html>

JavaScript Code:

function even_digits(num) {
  var ctr = 0;
  while (num) {
    ctr += num % 2 === 0;
    num = Math.floor(num / 10);
  }
  return ctr;
}

console.log(even_digits(123));
console.log(even_digits(1020));
console.log(even_digits(102));

Sample Output:

1
3
2

Flowchart:

Flowchart: JavaScript - Find the number of even digits in a given integer

ES6 Version:

function even_digits(num) {
  let ctr = 0;
  while (num) {
    ctr += num % 2 === 0;
    num = Math.floor(num / 10);
  }
  return ctr;
}

console.log(even_digits(123));
console.log(even_digits(1020));
console.log(even_digits(102));

Live Demo:

See the Pen javascript-basic-exercise-130 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to find the smallest prime number strictly greater than a given number.
Next: Write a JavaScript program to create an array of prefix sums of the given array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter

JavaScript: Tips of the Day

Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters)

Example:

const isAnagram = (str1, str2) => {
  const normalize = str =>
    str
      .toLowerCase()
      .replace(/[^a-z0-9]/gi, '')
      .split('')
      .sort()
      .join('');
  return normalize(str1) === normalize(str2);
};
console.log(isAnagram('iceman', 'cinema')); // true

Output:

true