Essential JavaScript

Interpolation

Adding strings together in JavaScript is easy. However, it can become tedious if we want to add many strings together:

function talkAboutFish(fishCount, fishType) {
  return 'I have ' + fishCount + ' ' + fishType + ' fish.';
}

There is a way to make this easier called interpolation. Interpolation is when we start with a single string and inject values into it. It is often simpler than adding many strings together.

Examples

Take this function as an example:

function talkAboutFish(fishCount, fishType) {
  return `I have ${fishCount} ${fishType} fish.`;
}

To add a value into the string, use a dollar sign and curly braces. The dollar sign and curly braces will be removed and only the value will remain.

Copy the function into the practice editor and try calling it with different values:

talkAboutFish(0, 'red');
talkAboutFish(1, 'blue');
talkAboutFish(3.5, 'silver');

Backticks Only

We can only interpolate strings that have backticks around them. This example won't work because it uses double quotes:

function getToDoListItem(product, seller) {
  return "Buy ${product} at ${seller}";
}
getToDoListItem('milk', 'grocery store');
// returns: 'Buy ${product} at ${seller}'

This is how the above example should look with backticks:

function getToDoListItem(product, seller) {
  return `Buy ${product} at ${seller}`;
}
getToDoListItem('milk', 'grocery store');
// returns: 'Buy milk at grocery store'

Learning Goals

Code Editor