Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

javascript - Back-tick vs single quote in js

Working on node.js (server side), I wonder if I should use all back-ticks (`) instead of the regular quotes (" or ') all the time since it will make the code consistent. Is there any specific reason for keeping different type of quotes for different things. Will it affect performance if all non-substitution quotes are converted to back-ticks?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

the back-tick allows you to use string templating for example:

var value = 4;
var str = `text with a ${value}`
// str will be  : 'text with a 4'

for " vs ' I say look at this post: https://stackoverflow.com/a/9959952/6739517

As for performance, it seems like it would be the same if you are just using back-ticks for plain strings. However when building strings it looks like concatenation is still the way to go. Take a look here:

2018 update: It seems that ES6 string templating can be faster than concatenation in some cases. Take a look at the following post for some hard numbers:

Are ES6 template literals faster than string concatenation?

2020 update: Generally speaking you should not be worried about performance when considering which type of quotation to use. There might be tiny differences but as many have pointed out these are such tiny improvements you are likely better off optimizing your code rather than considering which character to use. That said, this doesn't really answer the question of consistency. For me, I generally follow Airbnb's style guide. That is strings are always declared with single quotes (') unless you need to build a string then you should avoid concatenation and only use string templating with backticks (`). Finally, double quotes are reserved for JSON and HTML.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...