JavaScript Basics · Lesson 4 of 13

Strings

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:

MethodResult 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

  1. Create a variable greeting with a template literal, so that it holds exactly Welcome to Paris, Mia! built from the two variables.
  2. Print greeting.
  3. Print the city name in capital letters, using a method.
  4. Print the number of characters in name.
  • greeting is exactly Welcome to Paris, Mia!
  • It is built with a template literal that uses both variables
  • The greeting is printed
  • PARIS is printed, made with toUpperCase()
  • The length of the name, 3, is printed