0
0
JavascriptHow-ToBeginner · 3 min read

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.log with format specifiers like %s for strings, %d for numbers, and %o for 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 %o or JSON.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 SpecifierDescriptionExample
%sString placeholderconsole.log('Hello %s', 'World');
%d or %iInteger or number placeholderconsole.log('Age: %d', 25);
%fFloating point numberconsole.log('Price: %f', 9.99);
%oObject placeholderconsole.log('Object: %o', {a:1});
Template literalsEmbed variables with `${}` inside backticksconsole.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.