What Are Whitespace and Line Breaks in JavaScript



JavaScript, like many programming languages, allows whitespace and line breaks to improve code readability. While JavaScript generally ignores whitespace, line breaks can sometimes affect how the code is interpreted.

What is Whitespace in JavaScript?

The whitespace in JavaScript includes spaces, tabs, and newlines. The JavaScript engine ignores extra whitespace, which means that adding spaces between variables, operators, or keywords does not affect the execution of the code.

Example

For example, the following two code snippets are functionally identical ?

var employee = "Amit";
var employee="Amit";

Even though the first example has spaces around the assignment operator (=), JavaScript treats both lines the same way.

Line breaks in JavaScript

Line breaks in JavaScript occur when the code is written on multiple lines. JavaScript automatically interprets line breaks in most cases, but it can sometimes cause unexpected behavior, especially in strings and function calls.

Example

Consider the following example that uses a line break inside an alert() function ?

<!DOCTYPE html>
<html>
   <body>
      <p>Line-break in an alert box. Click below button.</p>
      <button onclick="alert('Hi
Welcome to Tutorialspoint')">Click</button> </body> </html>

Output


This ensures the alert message is displayed with a line break between "Hi" and "Welcome to Tutorialspoint" ?

Conclusion

JavaScript ignores extra whitespace, making it flexible for formatting code in a readable manner. However, line breaks should be carefully handled, especially in strings and function calls, to avoid unintended behavior.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-02-13T18:46:34+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements