Get the second Digit of a Number in JavaScript


Borislav Hadzhiev

Last updated: Oct 23, 2021


Photo from Unsplash

Get the second Digit of a Number #

To get the second digit of a number:

  1. Convert the number to a string.
  2. Access the string at index 1, using square brackets notation e.g. String(num)[1].
  3. Convert the result back to a number to get the second digit of the number.
const num = 98765; const secondDigitStr = String(num)[1]; console.log(secondDigitStr); // 👉️ 8 console.log(typeof secondDigitStr); // 👉️ string const secondDigitNum = Number(secondDigitStr); console.log(secondDigitNum); // 👉️ 1 console.log(typeof secondDigitNum); // 👉️ number

To be able to get the second digit of a number, we converted it to a string using the String object.

We can access the characters of a string, by using bracket notation and specifying an index.

Indexes are zero-based in JavaScript, meaning the index of the first character in a string is 0 and the last - str.length - 1.

Accessing the character at index 1 returns the second digit in the number, however it is still of type string.

The last step is to use the Number object to convert it back to a number.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.