Skip to main content

Command Palette

Search for a command to run...

Adding a Leading Zero in JavaScript

Published
1 min readView as Markdown
Adding a Leading Zero in JavaScript
J

I am a Senior Software Engineer. Google Developers Expert. Entrepreneur. Mountain Climber. Neil Diamond fanatic. Cat lover. Gardener. World traveler.

At work, I recently ran into a scenario where we were capturing a user's date of birth (DOB). This information is collected in 3 fields day, month, and year. If your DOB is January 7, 1962, people were inputting 1 for the month, 7 for the day, and 1962 for the year. This sounds good but our back-end database required both the month and day to be 2 digits. So I needed to find a way to add a leading zero for both of these fields.

Starting Data

let month = 1;
let day = 7;

My simple solution in one line is:

month = `0${month}`.slice(-2)

Let's walk through this code. This combines 0 with the value the user inputs for their month. Then it takes the right two digits and assigns this to the month.

But what if the user inputs the value 10 for their month? It still works. It will combine 0 with 10 to produce 010 and then it takes the right two digits which is 10.

Let's Connect

Thanks for reading my article today. If you like my content, please consider buying me a coffee ☕.

A
Ajay3y ago

Short and simple. I implemented the same functionality with if-else conditions and it was verbose, but you just made it very simple - one line. Thanks for the sharing it Jennifer Bland

1
J

Ajay,

I bet my old code is the same as yours. The more I programmed, I learned how to shorten it.

More from this blog

All Things Tech

75 posts

I am a Senior Software Engineer. Google Developers Expert. Entrepreneur. Mountain Climber. Neil Diamond fanatic. Cat lover. Gardener. World traveler.