Is there a downside to using ES6 template literals syntax without a templated expression?

偶尔善良 提交于 2019-11-26 08:35:00

问题


Is there a reason (performance or other) not to use backtick template literal syntax for all strings in a javascript source file? If so, what?

Should I prefer this:

var str1 = \'this is a string\';

over this?

var str2 = `this is another string`;

回答1:


The most significant reason not to use them is that ES6 is not supported in all environments.

Of course that might not affect you at all, but still: YAGNI. Don't use template literals unless you need interpolation, multiline literals, or unescaped quotes and apostrophes. Much of the arguments from When to use double or single quotes in JavaScript? carry over as well. As always, keep your code base consistent and use only one string literal style where you don't need a special one.




回答2:


Code-wise, there is no specific disadvantage. JS engines are smart enough to not have performance differences between a string literal and a template literal without variables.

In fact, I might even argue that it is good to always use template literals:

  • You can already use single quotes or double quotes to make strings. Choosing which one is largely arbitrary, and you just stick with one. However, it is encouraged to use the other quote if your string contains your chosen string marker, i.e. if you chose ', you would still do "don't argue" instead of 'don\'t argue'. However, backticks are very rare in normal language and strings, so you would actually more rarely have to either use another string literal syntax or use escape codes, which is good.

    For example, you'd be forced to use escape sequences to have the string she said: "Don't do this!" with either double or single quotes, but you wouldn't have to when using backticks.

  • You don't have to convert if you want to use a variable in the string in the future.

However, those are very weak advantages. But still more than none, so I would mainly use template literals.

A real but in my opinion ignorable objection is the one of having to support environments where string literals are not supported. If you have those, you would know and wouldn't be asking this question.




回答3:


Always use string literals. In this case YAGNI is not correct. You absolutely will need it. As some point, you will have add a variable to your string, at which point you will either need to change single quotes to backtickets, or use the dreaded '+'.



来源:https://stackoverflow.com/questions/37777677/is-there-a-downside-to-using-es6-template-literals-syntax-without-a-templated-ex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!