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
andage
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}.`);