How to add new line in JavaScript

Learn how to add new line in JavaScript, both for console output and DOM output

Posted on April 13, 2021


There are two ways to add a new line in JavaScript depending on the output you wish to achieve. This tutorial will show you how to add a new line both for the JavaScript console and the DOM.

Adding a new line to the console output

If you want to add a new line when printing some words to the JavaScript console, you can use the \n symbol, which stands for new line.

Here’s an example:

let str = "Hello World!\nThis is my string";

console.log(str);

The output will be as follows:

"Hello World!
This is my string"

Alternatively, you can also add a new line break using Enter when you use the template string syntax as follows:

let str = `Hello World!
This is my string
Adding new line using template string`;

console.log(str);

The output of the code above will be as follows:

"Hello World!
This is my string
Adding new line using template string"

Next, let’s learn how to add new line to the DOM output

Adding a new line to the DOM output

When you need to output a new line for a web page, you need to manipulate the DOM and add the <br> HTML element so that the text will be printed below.

For example, you can write a JavaScript command as follows:

document.write("Hello World!<br/>This is my string");

The output to the <body> tag will be as follows:

<body>
  Hello World!
  <br />
  This is my string
</body>

Knowing this, you can manipulate the text of an HTML element to add a new line by changing the innerHTML property and adding the <br/> element.

The code in <script> tag below shows how you add a new line to a <div> with the id myDiv:

<body>
  <div id="myDiv"></div>
  <script>
    let element = document.getElementById("myDiv");
    element.innerHTML = "Hello World!<br/>This is my string";
  </script>
</body>

The output to the <div> tag will be as follows:

<div id="myDiv">
  Hello World!
  <br />
  This is my string
</div>

And that’s how you can add a new line using JavaScript for different outputs.

Related articles:

Grab the free JavaScript book today 👍

Learn the building blocks of JavaScript programming language like data types, functions, objects, arrays and classes.

Use the knowledge from the book to build a small but solid program.

Learn more