Skip to main content
eLearner.app
Module 2 · Lesson 1 of 45/32 in the course~8 min
Module lessons (1/4)

Strings and template literals

Strings are sequences of characters. In JavaScript you can delimit them in three ways, all equivalent to the engine — but with one superpower reserved for backticks:

JS
'single quotes';
'double quotes';
`backticks — template literals`;

Single and double quotes are interchangeable: use whichever lets you avoid escaping the other character in your text:

JS
'L\'isola'; // the apostrophe needs to be escaped
"L'isola"; // here it doesn't
"He said \"hi\"";
'He said "hi"';

Escape characters

Inside any string you can insert "non-printable" characters with a backslash:

  • \n — newline
  • \t — tab
  • \\ — a literal backslash
  • \' / \" — literal single / double quote
JS
console.log('line 1\nline 2');
// line 1
// line 2

Template literals: the syntax you want to use by default

Backticks unlock two things that are impossible with the other delimiters:

  1. Multiline strings without escapes: literal newlines are allowed.
  2. Interpolation: inside ${ … } you can place any JS expression and its value gets pasted into the result.
JS
const nome = 'Anna';
const eta = 28;

const messaggio = `Ciao ${nome}, hai ${eta} anni.
Fra un anno ne avrai ${eta + 1}.`;

The expression inside ${ … } doesn't have to be a simple name: it can be anything that produces a value, including function calls and operators.

Concatenation with +

Historically strings were composed with +. It still works, and is useful in rare cases (e.g. building a string in multiple steps):

JS
const a = 'Ciao';
const b = 'mondo';
a + ', ' + b + '!'; // 'Ciao, mondo!'

Try it

Exercise#js.m2.l1.e1
Attempts: 0Loading…

Given `name = 'Luca'` and `age = 30`, compose with a template literal the string 'Luca ha 30 anni.' (exactly this text) as the last expression.

Loading editor…
Show hint

Use backticks and ${...} interpolation to insert values into the string.

Solution available after 3 attempts

Review exercise

Exercise#js.m2.l1.e2
Attempts: 0Loading…

Given two prices `p1 = 7.5` and `p2 = 3.20`, return as the last expression the string 'Totale: 10.7 euro'.

Loading editor…
Show hint

Inside ${...} you can put any expression, including p1 + p2.

Solution available after 3 attempts