How to Format Console Output in JavaScript: Syntax and Examples
In JavaScript, you can format console output using
console.log with template literals (backticks and ${}) or placeholders like %s and %d. Template literals allow embedding variables directly in strings for clear and readable output.Syntax
You can format console output in two main ways:
- Template literals: Use backticks
`and embed variables with${variable}. - Placeholders: Use
console.logwith format specifiers like%sfor strings,%dfor numbers, and%ofor objects.
javascript
console.log(`Hello, ${name}!`); console.log('Age: %d, Name: %s', age, name);
Example
This example shows how to print a formatted message using template literals and placeholders.
javascript
const name = 'Alice'; const age = 30; // Using template literals console.log(`Name: ${name}, Age: ${age}`); // Using placeholders console.log('Name: %s, Age: %d', name, age);
Output
Name: Alice, Age: 30
Name: Alice, Age: 30
Common Pitfalls
Common mistakes include:
- Using single or double quotes instead of backticks for template literals, which prevents variable interpolation.
- Mismatching placeholders and variables in
console.log, causing incorrect or missing output. - Trying to format complex objects without using
%oorJSON.stringify.
javascript
const user = {name: 'Bob', age: 25}; // Wrong: no variable interpolation console.log('User: ${user.name}'); // Right: template literal console.log(`User: ${user.name}`); // Wrong: missing placeholder for object console.log('User: %s', user); // Right: use %o for object console.log('User: %o', user);
Output
User: ${user.name}
User: Bob
User: [object Object]
User: { name: 'Bob', age: 25 }
Quick Reference
| Format Specifier | Description | Example |
|---|---|---|
| %s | String placeholder | console.log('Hello %s', 'World'); |
| %d or %i | Integer or number placeholder | console.log('Age: %d', 25); |
| %f | Floating point number | console.log('Price: %f', 9.99); |
| %o | Object placeholder | console.log('Object: %o', {a:1}); |
| Template literals | Embed variables with `${}` inside backticks | console.log(`Name: ${name}`); |
Key Takeaways
Use template literals with backticks and ${} for clear and easy formatting.
Placeholders like %s and %d work inside console.log for formatted output.
Match placeholders with the correct variable types to avoid errors.
Use %o to print objects in a readable format.
Avoid using quotes instead of backticks when you want variable interpolation.