Breaking Long Code Lines

For best readability, programmers often like to avoid code lines longer than 80 characters. If a JavaScript statement does not fit on one line, the best place to break it is after a comma or an operator, such as an equal (=) sign or (+) sign. This code will return Hello Dolly:

   document.getElementById("demo").innerHTML =
   "Hello Dolly.";

You can also break up a code line within a text string with a single backslash, but keep in mind that the \ method is not a ECMAScript (JavaScript) standard. Some browsers do not allow spaces behind the \ character. This code will also return Hello Dolly:

   document.getElementById("demo").innerHTML = "Hello \
   Dolly!";

The safest (but a little slower) way to break a long string is to use string addition. This code will return Hello Dolly as well:

   document.getElementById("demo").innerHTML = "Hello " +
   "Dolly!";

Take care with the backslashes. You cannot break up a code line with a backslash (outside of a text string). This code will not return anything (and it will probably will mess up your whole webpage, as far as any other javascript codes are concerned):

   document.getElementById("demo").innerHTML = \
   "Hello Dolly!";

Back Table of Contents Next