How to Do String Interpolation in JavaScript
Replacement of placeholders with values inside of a string literal is called string interpolation.
In JavaScript, the template literals (also template string) wrapped in backticks (`) that supports the string interpolation and ${expression} as placeholder perform the string interpolation like this:
The placeholder has the following format: ${expressionToEvaluate}. The expression inside the placeholder can be:
- variables: ${myVar}
- operators: ${n1 + n2}, ${cond ? 'val 1' : 'val 2'}
- even function calls ${myFunc('argument')}
Example of operator:
The placeholder expression output is implicitly converted to a string. For example, a number in a placeholder is converted to a string:
It is important that any string that uses interpolation be wrapped in backticks (`), not “double quotes” or ‘single quotes’. When you use backticks, you create a Template Literal, which is just a string that can accept embedded code.