Categories
Modern JavaScript

Best of Modern JavaScript —Template Literals

Spread the love

Since 2015, JavaScript has improved immensely.

It’s much more pleasant to use it now than ever.

In this article, we’ll look at JavaScript template literals.

Template Literals

A template literal is a string literal where we can interpolate JavaScript expressions right into the string.

For example, we can write:

const firstName = 'james';
console.log(`Hello ${firstName}`);

Then we get:

'Hello james'

It’s delimited by backticks instead of single and double-quotes.

Escaping in Template Literals

The backslash is used for escaping inside template literals.

For example, we can write:

`\``

and get:

'`'

However, we can’t write:

`${`

since we’ll get a SyntaxError.

Other than that, they work like regular string literals.

Line terminators in template literals are always LF.

LF is the line feed character, which is n or U+000A which is used by Unix and macOS.

CR, which is r or U+900D is used by old Mac OS.

CRLF, which is rn is used by Windows.

They’re all normalized to LF in template literals.

Tagged Template Literals

Tagged template literals is putting a tag in front of a template literal.

For example, we can write:

tagFunction`Hello ${firstName} ${lastName}`

where tagFunction is a function that we call on the string.

It’s the same as writing:

`tagFunction(['Hello ',` `' '],` `firstName,` `lastName)`

The tag takes the template string and substitutions for the placeholder.

The substitutions are done at runtime.

But template strings are known statically at compile time.

Tag functions also gets the raw version which isn’t interpreted.

It also gets the final version where the backslashes are special.

Raw Strings

ES6 has the String.raw template tag for raw strings.

It returns the string with all the backslashes intact.

For example, we can write:

const str = String.raw`Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus fringilla mauris vel erat facilisis lacinia. n

Vivamus tincidunt, massa sit amet fermentum rhoncus, nibh mi convallis elit, eget bibendum eros ipsum elementum purus. Donec tristique ligula mi, non dapibus quam finibus et. Orci varius natoque penatibus et magnis dis parturient montes`

with the n intact.

This is useful whenever we need to keep the backslashes in our strings.

We can use the sh template tag to run shell commands.

For example, we can write:

`const` `proc` `=` ``sh`ps ax | grep ${pid}`;``

Packages like the sh Template Tag package provides us with the sh template tag to run commands with the tag.

Facebook GraphQL

Facebook Relay lets us make queries to a GraphQL API.

For example, we can use it by writing:

import React from "react"
import { createFragmentContainer, graphql, QueryRenderer } from "react-relay"
import environment from "./lib/createRelayEnvironment"
import ArtistHeader from "./ArtistHeader"

export default function ArtistRenderer({artistID}) {
  return (
    <QueryRenderer
      environment={environment}
      query={graphql`
        query QueryRenderersArtistQuery($artistID: String!) {
          # The root field for the query
          artist(id: $artistID) {
            # A reference to your fragment container
            ...ArtistHeader_artist
          }
        }
      `}
      variables={{artistID}}
      render={({error, props}) => {
        if (error) {
          return <div>{error.message}</div>;
        } else if (props) {
          return <Artist artist={props.artist} />;
        }
        return <div>Loading</div>;
      }}
    />
  );
}

using the example from https://relay.dev/.

We just pass in our own template string into the graphql tag to make the request.

Conclusion

Template strings are useful.

They let us interpolate expressions and call them with tags.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *