How to count digits of given number? JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

The requirements here are simple, we are required to write a JavaScript function that takes in a number and returns the number of digits in it.

For example −

The number of digits in 4567 is 4
The number of digits in 423467 is 6
The number of digits in 457 is 3

Let's write the code for this function −

Example

const num = 2353454;
const digits = (num, count = 0) => {
   if(num){
      return digits(Math.floor(num / 10), ++count);
   };
   return count;
};
console.log(digits(num));
console.log(digits(123456));
console.log(digits(53453));
console.log(digits(5334534534));

Output

The output in the console will be −

7
6
5
10
raja
Published on 31-Aug-2020 17:20:41
Advertisements