
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Counting number of 9s encountered while counting up to n in JavaScript
Problem
We are required to write a JavaScript function that takes in a number n. Our function should count and return the number of times we will have to use 9 while counting from 0 to n.
Example
Following is the code −
const num = 100; const countNine = (num = 0) => { const countChar = (str = '', char = '') => { return str .split('') .reduce((acc, val) => { if(val === char){ acc++; }; return acc; }, 0); }; let count = 0; for(let i = 0; i <= num; i++){ count += countChar(String(i), '9'); }; return count; }; console.log(countNine(num));
Output
Following is the console output −
20
- Related Articles
- Counting the number of 1s upto n in JavaScript
- Number of letters in the counting JavaScript
- Counting prime numbers from 2 upto the number n JavaScript
- Counting divisors of a number using JavaScript
- Counting steps to make number palindrome in JavaScript
- Counting number of words in a sentence in JavaScript
- Counting number of vowels in a string with JavaScript
- Counting number of paragraphs in text file using java\n
- Counting number of lines in text file using java\n
- Counting number of triangle sides in an array in JavaScript
- Counting Number of Dinosaurs in Python
- Counting the number of redundant characters in a string - JavaScript
- Implementing counting sort in JavaScript
- Counting matching substrings in JavaScript
- Counting n digit Numbers with all unique digits in JavaScript

Advertisements