JavaScript AcademyProfessional Engineering
Level 1 · FoundationsModule 2: Variables, Values and TypesLesson 7 of 150About 45 minutes

Lesson 7: Strings and template literals

01Opening question

How does a website turn a first name and an order number into a message like "Thanks, Ada! Order 1042 is on its way"?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

The backticks make a template literal. Each ${ } inserts a value into the text.

const name = "Ada";
const order = 1042;
console.log(`Thanks, ${name}! Order ${order} is on its way.`);

03Objective and prerequisites

Learning objective: Create strings, join them with + and template literals, use common string properties and methods (length, toUpperCase, trim, includes, slice) and escape special characters.

You need: Lesson 6: Variables with let and const

Skills practised: Values and variables, Strings.

04Explanation

A string is text. Write it between double quotes, single quotes or backticks: "hello", 'hello' or ` hello `. The quotes are not part of the text; they only mark where it starts and ends.

You can join strings with +: "Hello, " + name. You add the spaces yourself. A template literal (backticks) is easier: write the text and drop values in with ${ }, as in ` Hello, ${name} `.

Strings know things about themselves. text.length is the number of characters. Methods do work: text.toUpperCase(), text.trim() (removes spaces at both ends), text.includes("cart") and text.slice(0, 3) (the first three characters).

Methods return a new string; the original never changes. To keep the result, store it: const shout = text.toUpperCase();.

05Definitions

String
A text value written between quotes or backticks.
Template literal
A string in backticks that can insert values with ${ } and span several lines.
Concatenation
Joining strings with +.
Method
A function that belongs to a value, called with a dot: text.trim().
Index
The position of a character, starting at 0.
Escape sequence
A backslash code for a special character, such as \n (new line) or \" (a quote).

Open the full glossary

06Visual learning object

String manipulation laboratory. Type a string, apply methods one at a time and see the new string each method returns.

Loading the interactive object…

Open the full String manipulation laboratory page with its guided experiment.

07Examples

ex-007-01Three ways to build a message Browser-executable JavaScript

+ needs explicit spaces; a template literal reads like the final text.

const item = "Backpack";
const price = 39.99;
console.log("Item: " + item + ", price: " + price);
console.log(`Item: ${item}, price: ${price}`);
console.log(`Two of them cost ${price * 2}`);
Sample input
None
Expected output
Item: Backpack, price: 39.99 Item: Backpack, price: 39.99 Two of them cost 79.98
Common mistake
Forgetting the spaces inside the quotes when joining with +.
Try this
Add a line that prints the item name in capital letters inside a template literal.
Source
examples/ex-007-01-three-ways.js (repository pending publication)

ex-007-02Useful string methods Browser-executable JavaScript

Each method returns a new string or a value about the string. The original stays the same.

const raw = "  Blue T-Shirt  ";
const clean = raw.trim();
console.log(clean);
console.log(clean.length);
console.log(clean.toUpperCase());
console.log(clean.includes("Shirt"));
console.log(clean.slice(0, 4));
console.log(raw.length);
Sample input
None
Expected output
Blue T-Shirt 12 BLUE T-SHIRT true Blue 16
Common mistake
Expecting raw.trim() to change raw. Store the result in a new variable.
Try this
Print the last five characters with slice(-5).
Source
examples/ex-007-02-string-methods.js (repository pending publication)

ex-007-03Quotes, new lines and multi-line text Browser-executable JavaScript

A backslash lets you put special characters inside a string. Template literals can also span lines.

console.log("She said \"hello\"");
console.log('It\'s ready');
console.log("Line one\nLine two");
const receipt = `Receipt
Total: 12`;
console.log(receipt);
Sample input
None
Expected output
She said "hello" It's ready Line one Line two Receipt Total: 12
Common mistake
Closing the string early by using the same quote inside it without a backslash.
Try this
Rewrite the first line with single quotes so no backslashes are needed.
Source
examples/ex-007-03-escapes-and-lines.js (repository pending publication)

ex-007-04When + joins instead of adds Browser-executable JavaScript

If either side of + is a string, JavaScript joins text. This is the source of many "123" bugs.

console.log(2 + 3);
console.log("2" + 3);
console.log("Total: " + 2 + 3);
console.log("Total: " + (2 + 3));
console.log(`Total: ${2 + 3}`);
Sample input
None
Expected output
5 23 Total: 23 Total: 5 Total: 5
Common mistake
Adding numbers inside a + chain that already started with a string.
Try this
Predict what 1 + 2 + "3" prints, then run it.
Source
examples/ex-007-04-numbers-and-strings.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Fix the greeting

Turn a + chain into a template literal and fix the missing spaces.

const firstName = "Sam";
const points = 120;
console.log("Welcome back," + firstName + "you have" + points + "points");

Build a product code

Use slice, toUpperCase and length to transform text.

const productName = "  wireless mouse ";
// TODO 1: clean = productName without the spaces at the ends
const clean = productName;
// TODO 2: code = the first 3 letters of clean, in capitals
const code = clean;
console.log(`Code: ${code}`);
console.log(`Name length: ${clean.length}`);

Shipping label

Combine values into a multi-line label with a template literal.

const customer = "Lee Wong";
const street = "12 Harbour Road";
const city = "Port Elm";
const parcels = 2;

09Prediction

Commit to an answer first, then run the real code to compare.

const word = "Cart";
console.log(word.length);
console.log(word.toUpperCase());
console.log(word);
console.log("1" + 1);

What four lines are printed?

10Debugging investigation

The order summary runs words together

The checkout summary should read Ada ordered 3 items for 45 dollars. Customers see Adaordered3itemsfor45dollars.

const customer = "Ada";
const count = 3;
const total = 45;
const summary = customer + "ordered" + count + "items" + "for" + total + "dollars";
console.log(summary);

More cases in the Debugging Detective Laboratory

11Practical scenario

Order confirmation

Every online order confirmation is built from strings: the customer's name, the items and the total. A missing space or an unescaped quote shows up in front of every customer, so it pays to build messages with template literals.

const name = "Ada";
const items = 3;
console.log(`Thanks, ${name}! ${items} items are on their way.`);

12Knowledge check

1. What does this print?

console.log("js".toUpperCase());
  • JS
  • js
  • Js
  • An error

2. What does this print?

console.log("hi you".length);
  • 5
  • 6
  • 4
  • 7

3. What does ` Total: ${2 * 3} ` produce?

  • Total: ${2 * 3}
  • Total: 6
  • Total: 2 * 3
  • Total:6

4. Why does this not change name?

let name = "  Ada ";
name.trim();
console.log(name.length);
  • trim only works on numbers
  • trim returns a new string that is not stored
  • name must be let
  • trim removes all spaces

5. What does this print?

console.log("Shopping".slice(0, 3));
  • Shop
  • Shopp
  • hop
  • Sho

6. Both lines print the same text. Which is less error-prone for longer messages?

  • "Hi " + name + ", you have " + n + " items"
  • Hi ${name}, you have ${n} items
  • Both are equal
  • Neither works

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Fix the greeting: Prints the greeting; Uses a template literal
  • Build a product code: Prints the code and length; clean is trimmed; Works for another name (extra case)
  • Shipping label: Prints the three-line label; label is a string; Uses the variables
  • ex-007-01: output matches the documented expected output
  • ex-007-02: output matches the documented expected output
  • ex-007-03: output matches the documented expected output
  • ex-007-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-01-foundations/module-02-variables-values-and-types/lesson-007-strings-and-template-literals/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • Strings are text in quotes or backticks.
  • Template literals insert values with ${ } and can span lines.
  • length, trim, toUpperCase, includes and slice return new values; strings never change.
  • If either side of + is a string, + joins text.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation Template literals
Context: I know how to join strings with +.
Task: Explain template literals by converting four + expressions into template literals.
Constraints: Beginner level; include one multi-line example.
Expected behaviour: I can rewrite any + chain as a template literal.
Testing: Give me two + chains to convert, with answers hidden.
Code prediction String method drill
Context: I know length, trim, toUpperCase, includes and slice.
Task: Ask me eight short questions about what each call returns.
Constraints: Use product names as data; wait for my answers.
Expected behaviour: Each question has one exact answer.
Testing: Explain any I get wrong with the index positions.
Debugging Text joined wrong
Context: My total prints as "Total: 105" instead of "Total: 15".
Task: Help me understand why + joined the numbers.
Constraints: Ask questions; do not give the fix straight away.
Expected behaviour: I can explain left-to-right evaluation of + with strings.
Testing: Suggest a console.log that shows the type of each part.
Exercise generation Formatting challenges
Context: I finished the shipping label exercise.
Task: Create two exercises that format receipts or labels with template literals and string methods.
Constraints: Exact expected output, fictional data.
Expected behaviour: Each needs at least two string methods.
Testing: Include the expected output.
Code review Message builder review
Context: I wrote a function-free script that builds five customer messages.
Task: Review it for missing spaces, inconsistent quotes and repeated code.
Constraints: Keep it beginner level, no functions yet.
Expected behaviour: The messages are consistent and readable.
Testing: Point to line numbers.