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:
'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:
'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
console.log('line 1\nline 2');
// line 1
// line 2Template literals: the syntax you want to use by default
Backticks unlock two things that are impossible with the other delimiters:
- Multiline strings without escapes: literal newlines are allowed.
- Interpolation: inside
${ … }you can place any JS expression and its value gets pasted into the result.
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):
const a = 'Ciao';
const b = 'mondo';
a + ', ' + b + '!'; // 'Ciao, mondo!'Try it
Given `name = 'Luca'` and `age = 30`, compose with a template literal the string 'Luca ha 30 anni.' (exactly this text) as the last expression.
Show hint
Use backticks and ${...} interpolation to insert values into the string.
Solution available after 3 attempts
Review exercise
Given two prices `p1 = 7.5` and `p2 = 3.20`, return as the last expression the string 'Totale: 10.7 euro'.
Show hint
Inside ${...} you can put any expression, including p1 + p2.
Solution available after 3 attempts