String formatting in JavaScript is the process of constructing strings by embedding variables, expressions, or formatting values in a readable and maintainable way.
Common String Formatting Techniques
- Concatenation with
+operator: Join strings and variables manually. - Template Literals (Recommended): Use backticks
` `with${}to embed expressions. - String methods: Use methods like
padStart(),padEnd(), andtoFixed()for specific formatting.
1. Concatenation
Old style method by joining strings with +:
📌 Deep Dive: Concatenation
const name = "Anna";
const age = 25;
const message = "Hello, " + name + "! You are " + age + " years old.";
console.log(message);
2. Template Literals
Modern and cleaner way to embed expressions inside strings using backticks and ${}:
📌 Deep Dive: Template Literals
const name = "Anna";
const age = 25;
const message = `Hello, ${name}! You are ${age} years old.`;
console.log(message);
3. Padding Strings
Use padStart() and padEnd() to add characters to a string until it reaches a desired length:
📌 Deep Dive: String Padding
const id = "7";
console.log(id.padStart(4, "0")); // "0007"
console.log(id.padEnd(4, ".")); // "7..."
7...
4. Number Formatting with toFixed()
Format numbers to fixed decimal places for consistent display:
📌 Deep Dive: Number Formatting
const price = 9.8765;
console.log(price.toFixed(2)); // "9.88"
| Method | Use Case |
|---|---|
| Concatenation (+) | Simple joins, older code |
| Template Literals | Embedding variables & expressions, multiline strings |
| padStart() / padEnd() | Aligning strings, adding leading/trailing characters |
| toFixed() | Formatting numbers to fixed decimals |

💡 Best Practice
Prefer template literals for clear and concise string formatting. Use padding and number formatting methods to control output appearance.
⚠️ Watch Out
Using concatenation with complex expressions can become hard to read. Template literals improve readability and reduce errors.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which method is recommended for embedding variables into strings cleanly?
Question 2 of 2
What does padStart(5, "0") do to the string "42"?
Loading results...