The basics of syntax

INPUT · Slides

Dropping a variable into some text

01 / 06

A chain of + is hard to read

Once the + pile up, as in name + " is " + age, it gets hard to tell which bits are text and which are variables.

It is also easy to lose count of your quotes.

const name = "Yui";const age = 12;console.log(name + " is " + age);

Result

Yui is 12

02 / 06

Wrap it in backticks

This is where the backtick, ` `, comes in. Wrap your text in that instead of "` and you can drop variables straight inside it.

Write ${variableName} wherever you want one to go.

const name = "Yui";const age = 12;console.log(`${name} is ${age}`);

Result

Yui is 12

03 / 06

The finished sentence is right there

Put it next to the chain of + and you can see it: the shape of the finished sentence reads straight off the page.

This way of writing is called a template literal.

const item = "bread";const price = 150;console.log(`${item} costs ${price} yen`);

Result

bread costs 150 yen

04 / 06

You can do maths inside ${}

Inside ${} you can put not just a variable but a whole expression. The worked-out result is what lands in the text.

const price = 200;const count = 3;console.log(`total ${price * count} yen`);

Result

total 600 yen

05 / 06

Finding the backtick

` ` looks a lot like '` (a single quote) and they are easy to mix up. They are different characters, so take care.

On a phone keyboard it usually lives with the other symbols. In this editor you can also tap it from the row of symbol buttons above the keyboard.

06 / 06

Line breaks work too

Text wrapped in backticks has one more nice property. A line break where you typed it is a line break in the output.

Text wrapped in " cannot have one, so this earns its keep whenever you want more than one line.

const name = "Yui";console.log(`hello${name}`);

Result

hello
Yui