JavaScript Printing Basics

This article is a complementary resource to the Learn JavaScript Basics course.

JavaScript Printing Basics

In JavaScript, we use console.log() to display output on the console. For example,

console.log("Hello World!");

let firstName = "John";
console.log(firstName);

Displaying Multiple Values

You can display multiple values with a single console.log() statement by separating the values with commas (,). For example,

let age = 10;
console.log("John's age is", age);

// Output: John's age is 10

Here, you might think the space between "John's age is" and age is caused by the space after the comma. But that's not the case—JavaScript automatically adds whitespaces between values when displayed using a single console.log() statement.

Ignored Whitespaces

JavaScript also ignores whitespaces that aren't part of a string.

let age = 10;

console.log("John's age is"     ,     age);
console.log("John's age is",               age);
console.log("John's age is"               ,age);

Here, all console.log() statements produce the same output:

Output

John's age is 10
John's age is 10
John's age is 10

Template Literals

You can use template literals to gain more control over formatting:

let firstName = "John";
let age = 10;
console.log(`${firstName}'s age is ${age}`);

// Output: John's age is 10

Note: To create template literals, enclose the output within backticks (` `) instead of quotation marks. To embed a variable, enclose it in ${}.


Line Breaks

Using line breaks ensures your output is clean and well-formatted, making it easier to read.

There are multiple ways to add line breaks using console.log().

1. Using Multiple Statements

You can create a new line in the output by using separate console.log() statements for each line. For example,

console.log("Hello");
console.log("World!");

Output

Hello
World!

2. Using the Newline Character

The newline character (\n) allows you to break lines within a single console.log() statement. For example,

console.log("Hello\nWorld!");

Output

Hello
World!

3. Using Template Literals

Template literals let you format output exactly as it should appear, making it convenient for multi-line strings. For example,

console.log(`Hello
World
!`);

Output

Hello
World
!

Takeaway:

  • Use template literals for printing multiple variables, like console.log(Age: ${age}), as they provide better readability and formatting than separating values with commas.
  • For cleaner multi-line outputs, opt for template literals or the newline character (\n) rather than multiple console.log() statements.