DevPath · Learn to code ESPTEN

Text strings

Creating strings and template literals

Text is everywhere

A username, your app's welcome message, a URL, the label on a button... almost everything a user reads is text. In programming we call that text a string, and you'll be handling them constantly. Let's start with the basics.

What is a string?

A string is text: a sequence of characters. It is written between quotes. JavaScript accepts three forms:

const a = "double quotes";
const b = 'single quotes';
const c = `backticks (back quotes)`;

All three create the same type of value. Double and single quotes are equivalent; use one or the other as convenient (for example, single quotes if the text contains double quotes).

Concatenate with +

The classic way to join text is the + operator:

const name = "Ana";
const greeting = "Hello, " + name + "!";
console.log(greeting); // "Hello, Ana!"

It works, but with many variables it turns into a puzzle of quotes and + signs that's easy to get wrong: you drop a space, you miss a +... and now you're debugging.

Template literals: your new best friend

Here comes the genuinely useful moment. Using backticks (`) you can write the text in one go and drop values right where they belong with ${...}:

const name = "Ana";
const age = 25;
const phrase = `${name} is ${age} years old`;
console.log(phrase); // "Ana is 25 years old"

Inside ${ } you can put any expression, not just variables:

const price = 10;
console.log(`Total with tax: ${price * 1.21} €`);

In addition, template literals respect line breaks exactly as you write them, with no weird characters in the way. Read it out loud: ${name} is ${age} years old reads almost like a normal sentence. That's why they're the recommended way to build text nowadays: once you try them, you won't go back to +.

Examples

Concatenation vs template literal

const name = "Ana";
const age = 25;
console.log("Old: " + name + " (" + age + ")");
console.log(`Modern: ${name} (${age})`);

Expressions inside the template

const a = 4;
const b = 6;
console.log(`${a} + ${b} = ${a + b}`);
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
Length and access by index →