Introduction

This tutorial will show you how back-Tic syntax provides a powerful way of working with strings.

Template literals

Template literals introduced in ES6 use (``) instead of quotes, ("") or (’’) in declaring strings.

Example:

let name = `Anita`

Template literals allow us to:

  1. Define multiline strings
  2. Perform interpolation- Embed variables and expressions inside Strings
  3. HTML templates - https://styled-components.com/ employ template literals to create React components

1. Multiline strings

With string literals, it is possible to declare a string that spans multiple lines:

Example:

// a string spanning multiple lines
let multiline = `
this is a multiline
string
`

2. Intepolation

Template literals allow us to embed variables inside Strings using ${a variable here}

let firstName = 'Anita'
let lastName = 'Nderu'
console.log(`Her name is ${firstName} ${lastName}`) // Her name is Anita Nderu
// previously this would have been
console.log("Her name is " + firstName + " " + lastName)

For instance, Interpolation can be useful when embedding a token or values in a URL query string Example:

// test key = 4520i3-8v0o72-h88813-932503
// endpoint url format: http://proxycheck.io/v2/<ips>?key=111111-222222-333333-444444

// sample ips: 8.8.8.8, 37.60.48.2, 192.168.1

const checkIp = async () => {
  const ipAdresses = ['1.1.1.1.1', '37.60.48.2', '192.168.1', '8.8.8.8'] // sample ip adresses
  let ipData = ipAdresses.join() // '1.1.1.1.1', '37.60.48.2', '192.168.1', '8.8.8.8'
  const url = `http://proxycheck.io/v2/${ipData}?key=4520i3-8v0o72-h88813-932503`
  const response = await fetch(url, { method: 'post'})
  const data = await response.json()
  console.log(data)
}

checkIp()

Expressions inside Template literals

Template literals also allow us to embed expressions in strings:

const tipPercentage = 0.2
const itemsCost = 5500
let tip = `Tip total ${(cost * cost).toFixed(2)}`
// or simply
console.log(`The sum of 1 & 2 is ${ 1 + 2}`) // The sum of 1 and two is 3

3. HTML templates

Template literals can be used to perform “templating”, where values are embedded inside HTML “templates” on render.

For example:

  // possible code ommitted
   const $rowContainer = document.querySelector('#itemsRow')
    const itemListing = await ItemSource.fetchItemListing()

    itemListing.ps4Games.forEach(videoGame => {
       
      $rowContainer.innerHTML += `
          <div class='col-md-3'>
                  <div class='card'>
                  <h3>${videoGame.name}</h3>
                  <img src="${videoGame.image}"/>
                  <p>${videoGame.Description}</p>
                  <h4>ksh ${videoGame.price}</h4>
                  <Button class='btn btn-primary'>Add to Cart</Button>
                  <Button class='btn btn'>Add to WishList</Button>
              <div>
          </div>`
    })

Summary

  1. Template literals provide a powerful way of working with strings
  2. In template literals, we use back-tics (``) instead of quotes
  3. To embed an expression or a variable, we declare a string using `` back-ticks, use ${...} to embed the variable/expression.