String Formatting

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(), and toFixed() for specific formatting.

1. Concatenation

Old style method by joining strings with +:

📌 Deep Dive: Concatenation

JAVASCRIPT
const name = "Anna";
const age = 25;
const message = "Hello, " + name + "! You are " + age + " years old.";
console.log(message);
Output
Hello, Anna! You are 25 years old.

2. Template Literals

Modern and cleaner way to embed expressions inside strings using backticks and ${}:

📌 Deep Dive: Template Literals

JAVASCRIPT
const name = "Anna";
const age = 25;
const message = `Hello, ${name}! You are ${age} years old.`;
console.log(message);
Output
Hello, Anna! You are 25 years old.

3. Padding Strings

Use padStart() and padEnd() to add characters to a string until it reaches a desired length:

📌 Deep Dive: String Padding

JAVASCRIPT
const id = "7";
console.log(id.padStart(4, "0")); // "0007"
console.log(id.padEnd(4, "."));   // "7..."
Output
0007
7...

4. Number Formatting with toFixed()

Format numbers to fixed decimal places for consistent display:

📌 Deep Dive: Number Formatting

JAVASCRIPT
const price = 9.8765;
console.log(price.toFixed(2)); // "9.88"
Output
9.88
String Formatting Comparison
MethodUse Case
Concatenation (+)Simple joins, older code
Template LiteralsEmbedding variables & expressions, multiline strings
padStart() / padEnd()Aligning strings, adding leading/trailing characters
toFixed()Formatting numbers to fixed decimals
Illustration of string_formatting
Illustration of string_formatting

💡 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.