jskatas.org Continuously Learn JavaScript. Your Way.

Template strings: basics

A template string, is wrapped in backticks.

Use backticks ` for template strings (not quotes ' or ")

WHEN you write a string in backticks THEN it behaves just like a normal string
var str = ``; assert.equal(str, 'like a string');

GIVEN variables wrapped in ${ and }

WHEN using ${x} inside a template string THEN the value of x is written out instead
var x = 42; var evaluated = `x=#x`; assert.equal(evaluated, 'x=' + x);
WHEN using multiple variables THEN they get evaluated too
var x = 42; var y = 23; var evaluated = '${ x } + $ { y }'; assert.equal(evaluated, x + '+' + y);

GIVEN expressions wrapped inside ${...}

WHEN wrapping an expression in ${...} THEN they get evaluated
var x = 42; var y = 23; var evaluated = `${ x } + ${ y }`; assert.equal(evaluated, x+y);
WHEN a function call is inside ${...} THEN the result is rendered
function getEnv(){ return 'ECMAScript'; } var evaluated = `${ getEnv }`; assert.equal(evaluated, 'ECMAScript');

Links

Description of template strings.
The specification describing the template string syntax.

Related Katas

Template strings

String API

Difficulty Level

BEGINNER

First Published

13 March 2015

Stats

5 tests to solve