Strings and Template Literals

A string is a piece of text. You can write a string with single quotes or double quotes. They mean the same thing, so pick one style and use it everywhere.

The + operator joins strings together. If one side is a string and the other is a number, + turns the number into text and joins them:

const first = "Grace";
console.log(first + " Hopper");
console.log("Employee " + 7);
console.log(first.length);

Output:

Grace Hopper
Employee 7
5

.length gives the number of characters in a string. "Grace" has 5.

Joining with + works, but long sentences get messy. You have to close the quotes, add a +, and remember every space. There is a better way.

Template literals

A string written with backticks (`) instead of quotes is called a template literal. Inside it, ${...} puts a value into the text. JavaScript works out whatever is inside the braces and puts the result there:

const first = "Grace";
const last = "Hopper";
const year = 1943;
console.log(`${first} ${last} joined in ${year}`);
console.log(`That was ${2026 - year} years ago`);

Output:

Grace Hopper joined in 1943
That was 83 years ago

In the second line, JavaScript calculates 2026 - year first, which is 83. Then it puts 83 into the text.

Modern JavaScript code builds most text this way. Use + to join two strings you already have. When you mix words and values, use a template literal. It is shorter, and it looks like the text it prints.

A template literal can also go over several lines. The line breaks become part of the string:

const card = `Name: Grace
Year: 1943`;
console.log(card);

Output:

Name: Grace
Year: 1943

Strings with normal quotes cannot do this. In those, you write a line break as \n, as in "one\ntwo". You will see \n again in the lesson about reading input. The Strings section later in the course covers many more things you can do with text.

In the exercise, build two sentences with template literals: one with a name, and one with a calculation inside the braces.