javascriptjquerymultiline

What does a backslash at the end of a line do?


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!


Solution

  • 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
    }