Course outline · 0% complete

0/29 lessons0%

Course overview →

Strings and template literals

lesson 1-3 · ~9 min · 3/29

Strings, three kinds of quotes

Programs talk to people through text: log lines, error messages, receipts, chat replies. Assembling those messages out of fixed text plus changing values is a daily job, and JavaScript has a dedicated syntax for it that beats gluing pieces together with +.

JavaScript strings work like Python strings: text in quotes. Single 'hi' and double "hi" quotes are interchangeable. The third kind, backticks ` hi `, creates a template literal, and it is the one you will use constantly.

Before we combine strings we need a variable. In Python you wrote name = "Ada". In JavaScript you declare it with the keyword let:

let name = "Ada";

Variables get their own lesson (2-1). For now, let creates one.

Joining with + works like Python:

console.log("Hello, " + name + "!");

And .length is a property, not a function, so there are no parentheses: name.length gives 3 where Python used len(name).

Template literals are JavaScript's f-strings

In Python you wrote f"{name} is {age}". JavaScript's version uses backticks and ${...}:

let age = 36;
console.log(`${name} is ${age} years old`);

Anything inside ${...} is a full expression, so math works too: ` Next year: ${age + 1} `. Two rules to remember:

  • The quotes must be backticks. With normal quotes, ${name} prints literally.
  • The dollar sign comes before the brace: ${age}, not {age}.

Code exercise · javascript

Run this and compare the two outputs. The first line uses + joining, the second uses a template literal with an expression inside.

Code exercise · javascript

Your turn. Using the two variables and ONE template literal, print exactly: It is 21°C in Miami

Template literals can span lines

A normal quoted string must end on the line it started. A template literal may contain real line breaks and keeps them, because backticks were designed to hold whole blocks of output — receipts, emails, reports — without \n juggling:

const receipt = `Order #1042
Total: $18.50`;

Printing receipt gives two lines. The line break counts as one character in .length, exactly as \n did in Python.

Code exercise · javascript

Run it. One template literal holds a two-line receipt. Count the characters: 11 on the first line, 13 on the second, plus 1 for the line break itself.

Quiz

Which line prints Ada is 36 (and not the literal text ${name})?