Lodash _.pad() Method

Overview
What You’ll Learn
By the end of this tutorial, you’ll confidently use Lodash’s _.pad() method in real JavaScript projects.
01
Core syntax
_.pad(str, length, chars) centers fill.
02
Fixed width
Align columns in tables and logs.
03
Custom fill
Use '0', '-', or any repeat char.
04
vs padStart
Center vs left-only padding.
05
vs padEnd
Center vs right-only padding.
06
Production tips
Pick length based on max content width.
Fundamentals
What Is _.pad()?
It pads a string on the left and right until it reaches the specified length, using spaces by default.
💡
Beginner tipImport only what you need: import pad from "lodash/pad" keeps bundles small.
Foundation
📝 Syntax
_.pad(string, [length=0], [chars=' '])
import pad from "lodash/pad";
const original = "Hello";
const result = pad(original, 10);
console.log(JSON.stringify(result));
// -> '" Hello "'
Cheat Sheet
⚡ Quick Reference
| Task | Code pattern | Result |
|---|
| Center spaces | <code>_.pad('Hello', 10)</code> | " Hello " |
| Custom char | <code>_.pad('123', 6, '0')</code> | 001230 |
| Align names | <code>_.pad(name, maxLen)</code> | Column align |
| Left pad | <code>_.padStart(str, n, '0')</code> | Leading fill |
| Right pad | <code>_.padEnd(str, n, ' ')</code> | Trailing fill |
| Native | <code>str.padStart(n)</code> | ES2017 API |
Mutates?No
Returns new string
Default fillSpace
Third arg optional
RelatedpadStart / padEnd
One-sided
Reference
🧰 Parameters
Arguments accepted by _.pad():
stringPrimary
The input string to transform. Lodash coerces null and undefined to an empty string.
return valueNew string
A new string result. The original input is never mutated.
Hands-On
Examples Gallery
Practical _.pad() patterns with copy-ready code and interactive Try It Yourself labs.
📚 Getting Started
Pad strings with spaces or custom characters to a target length.
Example 1 — Basic center padding
Pad a short word with spaces on both sides to length 10.
const original = "Hello";
const padded = _.pad(original, 10);
console.log(JSON.stringify(padded));
// -> '" Hello "'
How It Works
Spaces are added evenly on both sides until the total length is 10.
📈 Practical Patterns
Fixed-width tables, numeric formatting, and column alignment.
Example 2 — Zero-fill padding
Pad a numeric string with leading zeros using a custom fill character.
const num = "123";
const padded = _.pad(num, 6, "0");
console.log(padded);
// -> "000123"
How It Works
For left-only zero fill, _.padStart is often clearer; _.pad centers by default.
Example 3 — Align a column of names
Pad each name to the same width for monospace table output.
const names = ["Alice", "Bob", "Charlie"];
const maxLen = Math.max(...names.map((n) => n.length));
names.forEach((name) => {
console.log(_.pad(name, maxLen) + " |");
});
// Alice |
// Bob |
// Charlie |
How It Works
Compute max width once, then pad every row for clean alignment.
Example 4 — Custom dash padding
Use a non-space fill character for visual separators.
const label = "OK";
const padded = _.pad(label, 8, "-");
console.log(padded);
// -> "--OK----"
How It Works
The fill string repeats; extra padding favors the right side.
🚀 Beyond the Basics
One-sided padding and native alternatives.
Example 5 — pad vs padStart vs padEnd
Compare center, left, and right padding for the same input.
const str = "Hello";
console.log(_.pad(str, 10, "-")); // --Hello---
console.log(_.padStart(str, 10, "-")); // -----Hello
console.log(_.padEnd(str, 10, "-")); // Hello-----
pad: --Hello---
padStart: -----Hello
padEnd: Hello-----
How It Works
Choose the helper that matches your alignment needs.
Example 6 — Native String.padStart()
Modern JavaScript provides built-in padding methods.
const id = "42";
console.log(id.padStart(5, "0")); // "00042"
console.log(_.padStart(id, 5, "0")); // "00042"
native: 00042
lodash: 00042
How It Works
Lodash is useful for consistent APIs across older runtimes and multi-char fill edge cases.
🧠 How _.pad() Works
1
Receive string and length
Lodash reads the source string and target length.
Input
2
Compute deficit
If the string is shorter, calculate how many fill chars are needed.
Measure
3
Split fill both sides
Padding is distributed to left and right (extra goes right).
Pad
=
Return new string
Original string is unchanged; padded result is returned.
Output
Important
📝 Notes
_.pad() centers content—use padStart/padEnd for one-sided alignment.- If length is less than string length, the result is truncated.
- Multi-character fill strings repeat as needed.
- For numeric zero-padding,
_.padStart(num, width, '0') is common. - Calculate column width from the longest value in a dataset.
- See also _.padEnd() and _.padStart().
Wrap Up
Conclusion
_.pad() is a practical Lodash string helper for everyday JavaScript tasks. Use the examples above as starting points in your own code.
Pro Tips
💡 Best Practices
✅ Do
- Compute max width from your data set
- Use padStart for zero-padded numeric IDs
- Use padEnd for right-aligned monospace columns
- Specify length explicitly for predictable output
- Test truncation when input exceeds target length
❌ Don’t
- Use _.pad when you only need left or right alignment
- Assume padding never truncates long strings
- Hard-code column widths that break with new data
- Mix pad helpers inconsistently in one table
- Forget monospace fonts when aligning console output
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about _.pad()
01
Both sides
Centered fill.
Basics02
Length
Target total size.
API03
Custom char
Third argument.
Fill04
padStart
Left padding.
Related05
padEnd
Right padding.
Related❓ Frequently Asked Questions
It pads a string on the left and right until it reaches the specified length, using spaces by default.
_.pad() centers padding on both sides. padStart adds to the beginning; padEnd adds to the end.
The string is truncated to the target length (Lodash behavior).
Yes. Pass a third argument such as '0' or '-' as the fill string.
No. Strings are immutable; a new padded string is returned.
Yes in modern JavaScript. Lodash offers consistent behavior and custom fill across older environments.
Did you know?
_.pad() adds fill characters to both sides of a string so the total length reaches your target—use _.padStart() or _.padEnd() for one-sided padding.
Practice _.pad() in the Live Editor
Open the Try It editor and run the examples with your own input.
Open Try It editor →About the author
Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
6 people found this page helpful