ES2015 Part 2: Variable declaration

Part 2 in the series of ES2015 looks at a new way of defining strings, with the ability to substitute variables into place-holders.

Template Strings

In JavaScript, strings can be created using a pair of double-quotes: " or a pair of single-quotes: ' With ES2015, there’s another quotation mark that can be used to define strings: the back tick: `

Strings declared with the back tick have some new options:

  • It is possible to insert variable substitutions or expressions. This is done by inserting a ${} inside the string. Any expression can be inserted between the { and }, whether it be a variable name, numeric expression or even the result of a function call
  • Strings can span multiple lines. It is not necessary to insert newline characters (\n). One can simply define a string that spans multiple lines that already includes the newline characters

Here’s an example:

 1    function count(legs) {
 2        return 2*4;
 3    }
 4
 5    function intro(person, school, animal) {
 6        return `Introducing:
 7        ${person} from ${school}.
 8        Owns ${count() + 1} ${animal}s`;
 9    }
10
11
12    intro("John", "MIT", "bird")

The call to the intro function will return the following string:

Introducing:
    John from MIT. 
    Owns 9 birds