White space in JavaScript

JavaScript does not care for white space. It just ignores it. However there is one exception to the rule: when the white space is in between quotes such as a string literal. Example:

var text = "the quick
brown fox
jumps over
the lazy dog";

If you test the above script on the Chrome’s Console (CTRL SHIFT j), JavaScript will throw an error: SyntaxError: Unexpected token ILLEGAL. We need to use the backslash \ as an escape character. An escape character is one which invokes an alternative interpretation on subsequent characters in a character sequence. In this case, the backslash will tell JavaScript to ignore the subsequent line break and just make it a continuous string:

var text = "the quick \
brown fox \
jumps over \
the lazy dog";

Notice how I included the space before the backslash and not after it. We only want to escape the line return. Now, when we call variable text it outputs the the correct sentence: “the quick brown fox jumps over the lazy dog

Advertisements

Author: tarau

technical writer, web technologies

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s