Odd use of backslash in Javascript string

One of my colleagues used a backslash when setting a property string value 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 line is to populate our container of shared common buttons when the user hovers over them:

self.html(obj.shareButtonsHtml);

      

I know that backslash is an escape character in JS. Can anyone explain why my colleague was using them here? Didn't he need to avoid carriage returns or breaks? He has since moved on to another company, so I can't ask him!

+3


source to share


3 answers


It avoids newline characters.

This is necessary if you want multi-line strings, otherwise JS will not recognize the next line as part of a string.

So, yes, he really "should have avoided carriage returns or line breaks." That's what he's doing there.

You can use string concatenation to spread strings across multiple lines, but that means additional operations every time you use the string. The performance difference is not very significant, it is mostly a matter of preference.



The reason multi-line bites usually don't work in JS is because the interpreter (in most cases *) appends ;

to the end of the line of code if it doesn't already exist. This is why ;

is optional, but also breaks multi-line lines.

* An exception will be object / array literals, ;

they are not added there, for example:

var obj = {
    a:1
}

      

+5


source


Backslashes are used to escape newlines. It can also be used on the command line, eg.

David Walsh wrote a great post on javascript multiline strings: http://davidwalsh.name/multiline-javascript-strings

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



From the blog:

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

+4


source


It just allows it to define a string on multiple lines ( \

executes a newline character).

+1


source







All Articles