How to Write New Line in JavaScript

Harshit Jindal Feb 02, 2024
  1. Add a New Line Using the Newline Character in JavaScript
  2. Add a New Line Using Template Literals in JavaScript
  3. Add a New Line Using HTML <br> Tag to DOM Output in JavaScript
How to Write New Line in JavaScript

We can add a new line in JavaScript in three ways depending on the situation and our desired output. This tutorial discusses all three scenarios.

Add a New Line Using the Newline Character in JavaScript

In JavaScript, the \n symbol stands for the newline character. If we need to print words in different lines on the console, we can use \n inside the string to introduce the line break.

Example:

let str = 'This is in line 1.\nThis is in line 2.';
console.log(str);

Output:

This is in line 1.
This is in line 2.

Add a New Line Using Template Literals in JavaScript

Template literals are JavaScript’s way of enabling the interpolation of variables and expressions into strings, quoted strings, and multi-line strings. They are enclosed in backticks, making it easier to introduce new lines in JavaScript.

Example:

let str = `This is in line 1.
This is in line 2.`;
console.log(str);

Output:

This is in line 1.
This is in line 2.

Add a New Line Using HTML <br> Tag to DOM Output in JavaScript

We can use the DOM to have a line break by using the <br> tag in HTML. But this method is specifically for web pages and doesn’t work on console.

Example:

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

Output:

Hello World!
This is my string

Here, we select an HTML element and add a string with line break as its inner HTML.

Harshit Jindal avatar Harshit Jindal avatar

Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.

LinkedIn