JavaScript Strings
You should know that in JavaScript you cannot simply write a multilined code chunk, i.e. something like this:
var str = 'hello world'; |
This will result in an error, which can be a problem when you deal with large strings. Imagine a string containing some HTML that should be injected via innerHTML. Now one possible solution is to concatenate two or more strings, by splitting the initial string.
var str = 'hello' + 'world'; |
Howerver this solution result in some additional operations like concatenation. It can be very nice if there was something like the PHP multiline string format.
The PHP Example
In PHP you have the same use case with strings. You can have a string concatenated over multiple lines, but you cannot split lines like so:
// the following line is wrong $str = 'hello world'; // a possible solution to the line above is $str = 'hello' . 'world'; // which is very similar to the js solution in the second example // ... but in PHP there is the so called HEREDOC $str = <<<EOD hello world EOD; |
The heredoc gives us the power to write multiline strings.
The JavaScript Trick
Actually in JavaScript there is something that’s exactly what Heredoc is meant to be for PHP. Take a look at the last example:
var text = <> this <br /> is my multi-line text </>.toString(); document.body.innerHTML = text; |
Thus you can write multiline strings in the JavaScript code.