It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 15 - Template Literals in JavaScript

In this tutorial, I spoke of modern JavaScript, in particular, string concatenation versus template literals. It's an important feature in JavaScript that you will definetely find yourself using over and over.

Let's look at how to use them:

  const name = "Alice";
  const age = 25;

  console.log(`My name is ${name} and I am ${age} years old.`);

Explanation:

  • Template literals use backticks ( ` ) instead of quotes.
  • They allow embedding variables using ${variable}.
  • This makes string formatting easier compared to concatenation (+).
  • console.log("My name is " + name + " and I am " + age + " years old."); is now cleaner with template literals.

Try your hand:

1. Create a File:

Create a new file named lesson15-template-literals.html.

2. Write the Code:

Copy and paste the following code into your file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lesson 15 - Template Literals</title>
</head>
<body>
    <script>
        const name = "Alice";
        const age = 25;

        console.log(`My name is ${name} and I am ${age} years old.`);
    </script>
</body>
</html>

Save the file in your folder.

3. Preview the File:

  • Open the file in your browser and access the developer console.
  • Observe the output:
My name is Alice and I am 25 years old.

4. Experiment:

  • Try changing name and age to your details.
  • Try a multiline string without using \n:
const message = `Hello!
Welcome to JavaScript lessons.
Enjoy learning!`;

console.log(message);
  • Try using an expression inside a template literal:
const a = 5, b = 3;
console.log(`The sum of ${a} and ${b} is ${a + b}.`);