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?



JavaScript: Tips of the Day

Classes/function constructors

class Person {
  constructor() {
    this.name = 'Owen';
  }
}

Person = class AnotherPerson {
  constructor() {
    this.name = 'Eddie';
  }
};

const member = new Person();
console.log(member.name);

We can set classes equal to other classes/function constructors. In this case, we set Person equal to AnotherPerson. The name on this constructor is Eddie, so the name property on the new Person instance member is "Eddie".

Ref: https://bit.ly/3jFRBje