3

One of my colleagues used backslashes when setting the string value of a property in a JS object:

shareButtonsHtml : '\
    <span class="share-fb">\
        <a href="#" class="fb-share"><span class="fb-share-icon"></span>Share</a>\
        <span class="fb-share-count"><i></i><u></u>0</span>\
    </span>\
    <div class="share-twitter"> \
        <iframe class="share-twitter-iframe" \
                allowtransparency="true" frameborder="0" scrolling="no" \
                src="https://platform.twitter.com/widgets/tweet_button.html" \
                style="width:130px; height:20px;"></iframe> \
    </div> \
    <div class="share-google"> \
        <div class="g-plusone" data-size="small" data-annotation="none"></div> \
    </div>',

The only thing we do with this string is populate our social share buttons container when the user mouseovers them:

self.html(obj.shareButtonsHtml);

I know backslash is an escape character in JS. Can anyone explain why my colleague used them here? Surely he didn't need to escape the carriage return or line break? He's since moved on to another company, so I can't ask him!

And Finally
  • 5,602
  • 14
  • 70
  • 110

3 Answers3

5

He's escaping newline characters.

That's required if you want multiline strings, otherwise JS wouldn't recognise the next line as part of the string.

So, yes, he did in fact "need to escape the carriage return or line break". That's exactly what he's doing there.

You can use string concatenation to spread strings over multiple lines, but that means extra operations each time you use the string. The performance difference not very significant, it's mostly a matter of preference.

The reason multiline stings don't normally work in JS is because the interpreter (in most cases*) adds a ; to the end of the line of code, if it isn't there already. This is why the ; is optional, but it also breaks multiline strings.

* An exception would be object / array literals, ;'s aren't added there, for example:

var obj = {
    a:1
}
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
4

The backslashes are used to escape the newlines here. It can also be used in the command line for example.

David Walsh has written an excellent post about multiline javascript strings: http://davidwalsh.name/multiline-javascript-strings

It seems your colleague is actually using the preferred method above the 'slow and ugly' method using the plus (+) signs to concatenate the strings.

From the blog:

Adding a backslash at the end of each line tells the JavaScript engine that the string will continue to the next line, thus avoiding the automatic semicolon insertion annoyance.

Robin van Baalen
  • 3,632
  • 2
  • 21
  • 35
1

This simply allows him to define the string on multiple lines (the \ is escaping the "new line" character).

Jan Hančič
  • 53,269
  • 16
  • 95
  • 99