Interpolation in template literals
JavaScriptAll snippets in this category →
Posted on Backticks turn strings into “template literals” in JavaScript. They allow you to interpolate variables, the results of calculations, and even the return values of function calls.
const age = 4
// the “old” way to get the value of `age` into a strings
const concatenation = "Little Bobby is " + age + " years old."
// use `${expression}` to do the same in a template literal
const interpolation = `Little Bobby is ${age} years old.`
// an expression can be a calculation
const withCalculation = `Next year, Bobby will be ${age + 1} years old.`
// you can even use the return value of a function call in an expression
const withFunctionCall = `${age} years are ${yearsInDays(age)} days.`
const age = 4
// the “old” way to get the value of `age` into a strings
const concatenation = "Little Bobby is " + age + " years old."
// use `${expression}` to do the same in a template literal
const interpolation = `Little Bobby is ${age} years old.`
// an expression can be a calculation
const withCalculation = `Next year, Bobby will be ${age + 1} years old.`
// you can even use the return value of a function call in an expression
const withFunctionCall = `${age} years are ${yearsInDays(age)} days.`
const age = 4
// the “old” way to get the value of `age` into a strings
const concatenation = "Little Bobby is " + age + " years old."
// use `${expression}` to do the same in a template literal
const interpolation = `Little Bobby is ${age} years old.`
// an expression can be a calculation
const withCalculation = `Next year, Bobby will be ${age + 1} years old.`
// you can even use the return value of a function call in an expression
const withFunctionCall = `${age} years are ${yearsInDays(age)} days.`
const age = 4
// the “old” way to get the value of `age` into a strings
const concatenation = "Little Bobby is " + age + " years old."
// use `${expression}` to do the same in a template literal
const interpolation = `Little Bobby is ${age} years old.`
// an expression can be a calculation
const withCalculation = `Next year, Bobby will be ${age + 1} years old.`
// you can even use the return value of a function call in an expression
const withFunctionCall = `${age} years are ${yearsInDays(age)} days.`