loading...

re: What is the difference between using ` and "/' for strings in JavaScript? VIEW POST

FULL DISCUSSION
 

In JS, strings delimited with backticks are called 'template strings'. They're handled specially by the interpreter in that you can put expressions (literally any valid JS expression, including IFFE's) inside ${} in a template string, and they will be evaluated and the results substituted into the string exactly where they were. This functionality was added as part of ECMAScript 6, and you can see availability info on Can I Use?.

The idea here is that instead of having to go through concatenating multiple strings and non-string values to assemble a larger string (log message, HTML snippet, etc), you can instead use a template string and avoid the overhead of string concatenation. In essence, it's the same idea as format strings in other languages (for example sprintf() in C/C++, or format() in Python).

Note that this is not exactly a JS specific construct. A number of languages have something similar. For example, in GNU bash, you can wrap a statement in $() in a double-quoted string to get similar behavior, and Elixir lets you do the same thing in any string using #{}.

 

Could you theoretically put an alert() statement in these strings to run it? or does it only use the return value?

code of conduct - report abuse