What Are Whitespace and Line Breaks in JavaScript



JavaScript like other programming languages, permits whitespace and line breaks to make the code more readable. Although JavaScript tends to ignore whitespace, line breaks at times influence the way in which the code is presented.

What is Whitespace in JavaScript?

Whitespace in JavaScript comprises newlines, tabs, and spaces. JavaScript's engine disregards excess whitespace, i.e., inserting spaces between variables, operators, or keywords doesn't influence the code's execution.

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 happen when code is split across more than one line. JavaScript interprets line breaks automatically in the majority of cases, but sometimes it leads to unexpected behavior, particularly in function calls and strings.

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 also ignores additional whitespace so that code can be freely formatted in a readable manner. Line breaks, though, needed to be treated carefully, particularly within strings and function calls, to prevent unexpected behavior.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-05-15T19:38:15+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements