How To Next Line In Javascript

When working with JavaScript, there are often times when we need to display content on multiple lines. JavaScript doesn’t automatically interpret line breaks or new lines in the same way as HTML. In this blog post, we will explore different ways to add a new line in JavaScript.

1. Using the newline character (\n)

The most common way to add a new line in JavaScript is by using the newline character \n. The newline character is used to represent a line break in a text string and is often used in programming languages to display content on multiple lines.

Here’s an example:

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

This would output the following:

    This is line 1.
    This is line 2.
    This is line 3.
    

2. Using template literals (“)

Another way to add a new line in JavaScript is by using template literals (backticks). Template literals were introduced in ECMAScript 6 (ES6) and allow you to embed expressions within string literals, as well as easily create multi-line strings.

Here’s an example:

    let multiLineText = `This is line 1.
    This is line 2.
    This is line 3.`;
    console.log(multiLineText);
    

This would output the same result as the previous example:

    This is line 1.
    This is line 2.
    This is line 3.
    

3. Adding new lines in HTML with JavaScript

When working with JavaScript and HTML, you may want to add a new line in HTML using JavaScript. In this case, you can use the HTML line break tag <br> to create a new line in your output.

Here’s an example:

    let multiLineText = 'This is line 1.<br>This is line 2.<br>This is line 3.';
    document.getElementById('output').innerHTML = multiLineText;
    

This would output the following in your HTML:

    This is line 1.
    
This is line 2.
This is line 3.

In conclusion, there are different ways to add a new line in JavaScript depending on the context and your requirements. You can use the newline character, template literals or the HTML line break tag to achieve the desired output.