padStart()

ES2017+

Pads the current string from the start with another string until the resulting string reaches the given length.

Syntax

string.padStart(targetLength, padString)

Parameters

targetLength number

The length of the resulting string

padString string optional

The string to pad with (default: space)

Return Value

string

The padded string

Examples

JavaScript
const num = '5';
console.log(num.padStart(3, '0'));
console.log('abc'.padStart(6, '123'));
Output:
// '005' '123abc'

📌 When to Use

Use padStart() for zero-padding numbers, formatting fixed-width displays, aligning text in console output, or creating properly formatted codes like time (09:05), dates, or IDs.

⚠️ Common Mistakes

Forgetting to convert numbers to strings before padding: (5).padStart(2, "0") fails; use String(5).padStart(2, "0").

Not understanding that if the string is already longer than targetLength, it returns the original string unchanged.

Using padStart() when padEnd() is needed - padStart adds to the beginning (left-align), padEnd adds to the end (right-align).

✅ Best Practices

Use padStart() for consistent date/time formatting: String(hours).padStart(2, "0") + ":" + String(minutes).padStart(2, "0").

For numeric formatting, consider if toLocaleString() might be more appropriate for locale-aware number formatting.

Default padding character is space, but explicitly specify it for clarity when needed.

⚡ Performance Notes

padStart() is optimized in modern engines. For formatting many numbers in a loop, the overhead is minimal. However, if you need to format millions of numbers, consider using a pre-computed lookup table for common values like "00" through "99".

🌍 Real World Example

Date/Time and Number Formatting

padStart() is essential for creating properly formatted timestamps, order numbers, invoice IDs, and any display that requires consistent digit alignment.

// Format time display (HH:MM:SS)
function formatTime(date) {
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${hours}:${minutes}:${seconds}`;
}

console.log(formatTime(new Date())); // '09:05:32'

// Generate order/invoice numbers
function generateOrderId(sequence) {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const seq = String(sequence).padStart(5, '0');
  return `ORD-${year}${month}${day}-${seq}`;
}

console.log(generateOrderId(42)); // 'ORD-20240115-00042'

// Format binary, octal, or hex numbers
function formatBinary(num, bits = 8) {
  return num.toString(2).padStart(bits, '0');
}

console.log(formatBinary(5));   // '00000101'
console.log(formatBinary(255)); // '11111111'

// Align numbers in console output
function printTable(items) {
  const maxNameLength = Math.max(...items.map(i => i.name.length));
  items.forEach(item => {
    const name = item.name.padEnd(maxNameLength);
    const price = String(item.price).padStart(8);
    const qty = String(item.qty).padStart(4);
    console.log(`${name} | $${price} | x${qty}`);
  });
}

printTable([
  { name: 'Apple', price: 1.5, qty: 10 },
  { name: 'Banana', price: 0.75, qty: 25 }
]);

Related Methods