Search this site...

Whitespace in JavaScript

A whitespace character is an empty space (without any visual representation) on screen. Examples of whitespace characters include space characters, tabs, and line break characters. In JavaScript, use of excessive whitespace is ignored. For instance, the following JavaScript code,

a = b * d - c;

is equivalent to

a = b * d - c;

Thus both statements would be interpreted the same way. You might be asking be yourself why is whitespace important? Because whitespace is ignored in JavaScript, you can use it to benefit yourself by writing code that is more readable and understandable. The importance of whitespace though may not be realized in a smaller program. Suppose you had the following JavaScript code:

if (a > b) { document.write ("a is greater than b.");} else {document.write ("a is not greater than b"); }

As a programmer, the above code may be harder for you to follow but for the computer (specifically the interpreter) its more beneficial as much of the unnecessary space characters are eliminated. In the following code, however, we use reasonable amount of space for readability and understandability:

if (a > b)
{
document.write ("a is greater than b.");
}
else
{
document.write ("a is not greater than b");
}

From our above discussion, don't assume JavaScript ignores all excessive whitespace. The exception is to our rule is use of whitespace in strings. In strings, whitespace is preserved, as in:

var AString = "Thisis a string";