JavaScript · Unit 1: JavaScript basics · Lesson 4 of 5
Strings and template literals
Strings join with +: "Hello, " + name.
Opens this lesson in Code Academy. Lessons open one after another, and each unit opens when you pass the checkpoint quiz before it (you can take a checkpoint early to skip ahead). If this lesson is not open yet, the button shows you its unit on your map.
The idea
Strings join with +: "Hello, " + name. Template literals are often easier: write the text in backticks and drop values in with ${ }: `Hello, ${name}!`
Every string has a length: "code".length is 4. Methods do jobs on a string: toUpperCase(), toLowerCase(), trim() removes spaces from both ends and includes("x") checks for some text.
Careful: "5" + 3 gives "53", because + joins text when either side is a string. Turn text into a number with Number("5").
Worked example
JavaScript
const name = "Kai";
const city = "Lima";
console.log(`${name} lives in ${city}.`);
console.log(name.length);
console.log(city.toUpperCase());
console.log("5" + 3);
It prints
Kai lives in Lima.
3
LIMA
53
Key terms
- String
- Text in quotes. + joins strings; length counts their characters.
- Template literal
- A string in backticks with values inside ${ }, like `Hi, ${name}`.
Practise it in Code Academy
It has 4 exercises (predict the output, fill in the blank and write code from a prompt) and takes about 7 minutes. Every answer is checked as you go, and feedback names the exact mistake. Hints and the solution are there if you get stuck.
Every lesson is free: no ads, no lives and no paywall.