The goal of this tutorial is to get you up to speed with two powerful features introduced in ES6: Template Literals and Destructuring. We'll explore these features in detail and understand how they can be used to simplify our code.
By the end of this tutorial, you will:
A basic understanding of JavaScript syntax and ES6 features is recommended but not required.
Template literals are a new kind of string literals introduced in ES6. They are enclosed by the back-tick () and can contain placeholders, which are indicated by the dollar sign and curly braces (
${expression}
). The expressions in the placeholders and the text between them get passed to a function.
Example
let name = 'John Doe';
console.log(`Hello, ${name}!`); // Outputs: Hello, John Doe!
Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, maps and sets — which we're going to learn more about in a future ES6.io video —into their own variable. It allows us to extract properties from an object or items from an array, multiple at a time.
Example
let person = {name: 'John Doe', age: 25};
let {name, age} = person;
console.log(name); // Outputs: John Doe
console.log(age); // Outputs: 25
let fruit = 'apple';
let count = 5;
// Old way using normal string concatenation
console.log('I have ' + count + ' ' + fruit + 's.');
// New way using template literals
console.log(`I have ${count} ${fruit}s.`);
// Outputs: I have 5 apples.
In the above example, using template literals, we can embed the variables directly inside the string. It's more readable and cleaner.
let student = {name: 'John Doe', grades: [90, 85, 88]};
// Destructuring the object into separate variables
let {name, grades} = student;
console.log(name); // Outputs: John Doe
console.log(grades); // Outputs: [90, 85, 88]
In this example, we're extracting the 'name' and 'grades' properties from the 'student' object.
In this tutorial, we've covered template literals and destructuring, two powerful features introduced in ES6 that can greatly simplify your JavaScript code.
For further learning, you can look into other ES6 features such as arrow functions, rest/spread operators, and more.
Given an object {a: 1, b: 2, c: 3}
, use destructuring to create three new variables 'a', 'b', and 'c'.
Given the string 'Hello, John', use template literals to replace 'John' with a variable.
Given an array [1, 2, 3, 4, 5], use destructuring to create two new variables 'one' and 'two' with the first and second values of the array.
Solutions
// Exercise 1
let obj = {a: 1, b: 2, c: 3};
let {a, b, c} = obj;
// Exercise 2
let name = 'John';
console.log(`Hello, ${name}`);
// Exercise 3
let arr = [1, 2, 3, 4, 5];
let [one, two] = arr;
In each of the solutions above, we've applied the concepts of destructuring and template literals to solve the problem.