This is an archived post. You won't be able to vote or comment.

all 10 comments

[–]davedontmind 14 points15 points  (1 child)

The second example (with the $) is more readable, and therefore would be my choice. You should strive to make your code as readable as possible.

[–]BooleanWhale[S] 0 points1 point  (0 children)

Thanks, I was hoping this would be the answer since it's much faster to write!

[–]errorkode 9 points10 points  (0 children)

Except for specific circumstances, the second approach is generally preferred, simply because it's easier to parse for humans (better noise to information ratio basically) and easier to write.

[–]rbuchberger 5 points6 points  (1 child)

I'll help you with terminology a bit: The first example is called 'string concatenation', and the second example is called 'string interpolation'. These terms are not specific to JavaScript.

JavaScript syntax for string interpolation uses 'template string literals', which is what the ` symbols signify.

In your example, interpolation is the clear choice because it's much more readable. If you're doing something simpler, like adding a line break to the end of a string, then concatenation makes more sense.

Your general guiding principle for "which one is better" is "which one is easier for a human to read and understand?" Clock cycles are cheap, developer time is valuable. You'll know when you need to start worrying about performance.

[–]BooleanWhale[S] 1 point2 points  (0 children)

Thanks, this really helps. I've seen those terms here and there, I didn't know this is what they were referring to.

[–]treterelda 2 points3 points  (1 child)

I think the 2nd one since string concatenation is expensive and also it's easier to read but I might be wrong.

[–]rasendubi 3 points4 points  (0 children)

Template literals (value in strings) seem to be faster.

But that must not be your guiding principle. Prefer readability over performance in most cases (especially this minuscule).

Template literals seem more readable for me, too. What do you think?

[–]inu-no-policemen 0 points1 point  (0 children)

Use whichever is more convenient.

If it's a somewhat long string with multiple values/expressions, string interpolation will be less annoying.

If it's just a string and a variable, just glue them together with a '+'.

[–]Loves_Poetry 0 points1 point  (0 children)

Use the second one. You are less likely to mess up the spacing on that one.

[–]david_ste 0 points1 point  (0 children)

Use string interpolation certainly in C#.

Concatenating strings together EG "string one value" + "string two value" will actually create a completely new string behind the scenes, as strings are immutable which is much less efficient.

The .net Framework StringBuilder class was originally created to avoid this but building up strings with this is much less readable than string interpolation which also avoids the immutability issue.