Skip to the content

Text with variables

JavaScript · Unit 1: First steps

A text can also go inside backticks instead of quotes.

That way you can put the value of a variable inside it with ${}.

const name = "Emma";
console.log(`Hello, ${name}!`);

Prints

Hello, Emma!

A calculation fits inside ${}, not just a variable.

JavaScript works it out and puts the result into the text.

const price = 50;
console.log(`Two: ${price * 2}`);

Prints

Two: 100

prompt() reads what the person types.

It always gives back text (string), even if they type a number.

const name = prompt();
console.log(`Hello, ${name}`);

Prints

Hello, Emma

To do calculations with what they type, convert the text with Number().

const age = Number(prompt());
console.log(age + 1);

Prints

16

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

    const age = 17;
    console.log(`Age: ${age}`);
  2. 2. Complete the code

    Fill in so it prints I like pizza.

    const food = "pizza";
    console.log(`I like ${___}`);
  3. 3. Find the bug

    This program should greet Jack by his name. Which line has the error?

    const name = "Jack";
    console.log("Hello, ${name}");
  4. 4. Predict the output

    What does this code print?

    const a = 3;
    const b = 4;
    console.log(`${a} + ${b} = ${a + b}`);
  5. 5. Multiple choice

    What type is what prompt() gives back?

  6. 6. Predict the output

    If the person types 5, what does it print?

    const number = prompt();
    console.log(number + 1);
  7. 7. Complete the code

    The person types 4. Fill in so it prints 7.

    const number = ___(prompt());
    console.log(number + 3);
  8. 8. Put the lines in order

    The person types Jack. Order the lines to greet them by name.

  9. 9. Find the bug

    The person types 3 and then 4. The program should print their sum. Which line has the error?

    const a = Number(prompt());
    const b = prompt();
    console.log(`Total: ${a + b}`);
  10. 10. Predict the output

    The person types 35 (the price) and then 50 (what they pay). What does it print?

    const price = Number(prompt());
    const paid = Number(prompt());
    const change = paid - price;
    console.log(`Change: ${change}`);
Do this lesson

It opens in your browser. It is free and you do not need an account to start.

See all lessons →