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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With