In this article, we will learn how to pad a number with leading zeros in JavaScript using the `padStart()` method.

1. First, convert the number to a string.
2. Then, use the `padStart()` method to add the leading zeros to the number.

The `padstart()` method adds leading zeros to the start of the string until it reaches the specified target length.

JavaScript
``````function padZero(num, targetLength) {
}

const num = 1;

// 👇️ pad with 2 zeros

// 👇️ pad with 3 zeros

We created a reusable function `padZero()` that accepts a number and the target length for adding leading zeros to the number.

Since the `padStart()` method only works with string, we converted the number to a string.

The `padStart()` method adds a leading zero until it reaches to specified target length.

For example, If you have a string of length `3` and specify a target length of `5`, then `2` leading zeros will get added to the string and if the target length(`3`) is equal to the string’s length the string will not get padded.

JavaScript
``````console.log("111".padStart(5, '0')); // 👉️ 00111

If you want to add a leading zero regardless of the string’s length, you need to add the string’s length to the target length.

JavaScript
``````function alwaysPadZero(num, targetLength) {
targetLength = targetLength + String(num).length;
}

const num = 111;

// 👇️ pad with 2 zeros

// 👇️ pad with 3 zeros

We created a reusable function in the function we added the string’s length to the specified target length. Then we passed the updated target length to the `padStart` method. So it will always pad a number with a leading zero.

Note that the `padStart()` method returns a string. If you convert the result back to a number, the leading zeros will get removed.

JavaScript
``````function padZero(num, targetLength) {
}

You can use the `padStart()` method, to add leading zeros to the number in JavaScript. And note that the `padStart()` method returns the number as a string. 