How to Create a New Line in Backticks in JavaScript?

Estimated read time 1 min read

In JavaScript, you can create a new line in a template literal string by using the newline character \n. Here’s an example:

const newLine = `Line 1
Line 2
Line 3`;
console.log(newLine);

When you run this code, it will output the following:

Line 1
Line 2
Line 3

As you can see, each line is separated by a newline character, which is represented by \n. This allows you to create template literal strings with multiple lines.

In comparison to regular strings, template literals are more flexible and allow you to embed expressions directly in the string. Here’s an example:

const firstLine = 'Line 1';
const secondLine = 'Line 2';
const thirdLine = 'Line 3';
const newLine = `${firstLine}
${secondLine}
${thirdLine}`;
console.log(newLine);

In this example, three separate strings are defined and then used to build the final template literal string. The ${} syntax allows you to embed expressions directly in the string. The resulting output is the same as the previous example.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply