A string is a piece of text. You can write it with double quotes or single quotes, as long as both ends match:
const first = "Ada";
const last = 'Lovelace';
Joining strings
The + operator glues strings together. You have to add the spaces yourself:
const full = first + " " + last; // "Ada Lovelace"
Template literals
Joining with + gets messy quickly. A template literal is a string written with backticks (the key under Esc on most keyboards). Inside it, ${ } inserts the value of any variable or calculation:
const age = 36;
console.log(`${first} is ${age} years old.`);
console.log(`Next year: ${age + 1}`);
Length and methods
Every string knows its own length:
console.log(first.length); // 3
Strings also come with built-in tools called methods. You call a method with a dot, its name and brackets:
| Method | Result for "Hello" |
|---|---|
.toUpperCase() | "HELLO" |
.toLowerCase() | "hello" |
.includes("ell") | true |
.replace("H", "J") | "Jello" |
.trim() | removes spaces at both ends |
A method gives back a new string. The original is never changed.
A number in quotes is a string: "5" + "5" is "55", not 10.
Your Task
- Create a variable
greetingwith a template literal, so that it holds exactlyWelcome to Paris, Mia!built from the two variables. - Print
greeting. - Print the city name in capital letters, using a method.
- Print the number of characters in
name.
greetingis exactlyWelcome to Paris, Mia!- It is built with a template literal that uses both variables
- The greeting is printed
PARISis printed, made withtoUpperCase()- The length of the name,
3, is printed
Lesson complete!
Next Lesson: Making Decisions