new line in js

New Line in JavaScript

When working with JavaScript, it is common to add a new line in your code for clarity or organization purposes. There are a couple of ways to achieve this.

Method 1: Using the \n Escape Character

One way to add a new line in JavaScript is by using the \n escape character. This character represents a line break and can be added to a string to create a new line.


let message = "Hello\nWorld";
console.log(message);

This code will output:


Hello
World

Method 2: Using Template Literals

Another way to add a new line in JavaScript is by using template literals. Template literals allow you to embed expressions inside a string and provide an easy way to add line breaks.


let message = `Hello
World`;
console.log(message);

This code will output the same result as the previous example:


Hello
World

Using template literals makes it easier to include variables or complex expressions in your strings.

Conclusion

Adding a new line in JavaScript can be achieved using the \n escape character or template literals. Choose the method that works best for your code and style.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe