String Interpolation
In earlier versions of JavaScript, if we wanted to dynamically create strings, we needed to use the addition operator (+
):
const userName = 'Mai';const dynamicString = 'hello ' + userName + '!';
This works alright, but it feels pretty clunky at times, and can lead to bugs (eg. forgetting the space in Hello
).
Modern JavaScript allows us to embed variables and other expressions right inside strings:
const dynamicString = `hello ${userName}!`;
In order to use string interpolation, we need to use backticks (`
). If you're using a standard QWERTY North American keyboard, the key is found in the top-left corner, above “Tab”. It shares a key with the tilde (~
) character.
Strings created with backticks are known as “template strings”. For the most part, they function just like any other string, but they have this one super-power: they can embed dynamic segments.
We create a dynamic segment within our string by writing ${}
. Anything placed between the squiggly brackets will be evaluated as a JavaScript expression.
This means that we can do fancy things like this:
const age = 7;console.log(`Next year, you'll be ${age + 1} years old.`);
This creates the string “Next year, you'll be 8 years old.”.