Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Concatenation with String()

Tags:

javascript

We unfortunately do a lot of dynamic web page design by building strings of HTML using JavaScript and using document.write to output the data. I stumbled upon some code that one of my coworkers wrote that looks like the following:

var myString = String() + "this is my string" +
            "and I am doing a lot of string concatenation" +
            "doing this the worst way possible"

These lines go on and on, sometimes hundreds of lines of hard-coded HTML (with inline styles and missing end tags). The part that I am curious about is the String() . I've never seen this used before, and I've been writing JavaScript for a long time. I asked my co-worker what it was and he said that "It improves the performance of the string concatenation and while stepping through during debugging, you won't step on each line, but rather straight to the end".

Now I usually take these things with a grain of salt, but it made me curious... so I tested it out. Chrome, at least, always steps to the next statement regardless of the opening String() or not. So I know that point to at least be untrue.

So A. what is is? Its not really a constructor (as it were), and when I type String() into the console I get back the empty string "". And B. Is there any truth to his statement that it improves performance? And if so, why?

like image 685
pinkfloydx33 Avatar asked Oct 30 '22 19:10

pinkfloydx33


1 Answers

From String - JavaScript | MDN:

The String global object is a constructor for strings, or a sequence of characters.

As to whether using it as in your example improves performance, there are probably two things to keep in mind:

  • Whether it improves performance is probably dependent on the browser or other JavaScript runtime environment.
  • It probably doesn't improve performance enough to warrant using it.
like image 67
Kenny Evitt Avatar answered Nov 11 '22 06:11

Kenny Evitt