JavaScript Concatenation and Multiple Line Variables

JavaScript has some idiosyncrasies that make me want to pull my hair out sometimes. The worst part is that it doesn’t give you very helpful errors either. So diagnosing problems is very very slow at first and gets better only with practice and experience. Here are some of my newest observations of this finicky client side scripts.

Concatenation

When putting strings together you need to concatenate. In php you do it like this
$variableString = "I " . "want " . "a banana";
In javascript you use + instead of .
var variableString = "A " + "banana " + "sounds " + "meh ";

Multi-line variables

If your string variable is broken up over multiple lines it doesn’t matter in server side scripts. In javascript you’ll wind up with an error. SO multiline variables have to be in one line – or you’ll have to break it up with apostrophes and the + symbol. For example:
var reallyLongString = "This is a long string. This is a long string" + "This is a long string. This is a long string" + "This is a long string. This is a long string";
OR like this
var reallyLongString = "<b>This is a long string. This is a long string</b></ br></ br><b>This is a long string. This is a long string</b></ br></ br><b>This is a long string. This is a long string</b></ br></ br>";

Great Resources

  • Stack Exchange Concatenation
  • SRAJI multiple ways to concatenate
  • You may also like...