Interpolation in template literals

Posted on June 18, 2020

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.`

Continue reading

July 25, 2020JavaScript

Flattening nested arrays

We can un-nest arrays with a native function now. We can also define how many levels of nesting we want to take out, to a maximum of “all levels”.

Read full article
July 5, 2020JavaScript

Logging as objects

This neat little trick makes values logged to the console much more readable with a minor adjustment to how we log it.

Read full article
July 9, 2020JavaScript

Sorting numbers

The default behavior of sorting arrays assumes every value is a string. That leads to unexpected behavior when working with numbers.

Read full article

Read all snippets →