If you are looking to learn to react, it goes without saying that you should have your Javascript fundamentals figured out.
React also uses many ES6 concepts, which you should already be familiar with. In this tutorial, we will cover the most commonly used ES6 features you should know before learning React.Learning and understanding how to use these concepts will make your React journey fun and smooth.
Template Literals
ES6 has made working with strings easier. Rather than concatenating strings with the plus(+) sign, template strings provide an easier way.
// old way of joining strings
function sumNumbers(a, b) {
return "The sum of " + a + " and " + b + " is " + (a + b);
}
// using template literals
function sumNumbers(a, b) {
return `The sum of ${a} and ${b} is ${a + b}`;
}
Template literals also make it easier to work with multi strings
const multiLineString = `
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
`;
console.log(multiLineString);
Arrow Functions
Arrow functions make your code more concise. Let’s look at the differences between a normal function and an arrow function.
// Normal function
function myFunction() {
// Expression or statement
}
// Arrow function
const myArrowFunction = () => {
// Expression or statement
};
With an arrow function, rather than using the function keyword, you use the fat arrow(=>
), hence making it more concise.
If an arrow function returns a single expression, you can commit the curly braces and the return keyword.
If an arrow function takes a single argument, you can commit the double parathesis around the parameter.
// explicit return single expression
const add = (a,b) => a + b;
// ommit parantesis if single argument
const squared = a => a * a;
Arrow function are commonly used in array method such as map()
, filter()
, forEach()
, e.t.c
const names = ["Carol", "jane", "alice"];
const capitalizedNames = names.map((name) => name.toUpperCase());
console.log(capitalizedNames);
//output // [ 'CAROL', 'JANE', 'ALICE' ]
As you can see above, since we are only passing a single argument, we have committed the parentheses.
Destructuring Objects
Destructuring in JavaScript is the process of unpacking values from arrays or properties from objects into distinct variables. It is helpful when working with complex data structures, such as data from databases or an API.
For example, suppose you have a simple object describing a cat.
const cat = {
catName: 'Whiskers',
age: 3,
color: 'gray',
breed: 'Persian'
};
To get the cat name, you would normally use dot notation or bracket notation like this:
const cat = {
catName: "Whiskers",
age: 3,
color: "gray",
breed: "Persian",
};
``
// console.log(cat.catNname)
However, with object destructuring, you can unpack the properties into variable names and assign them to the cat object like this:
const { catNname, age, color, breed } = cat;
console.log(`My cat ${catNname} is ${age} moths old`)
The output will be:
My cat Whiskers is 3 months old
Destructuring Arrays
Destructuring arrays is similar to Destructuring objects;. Suppose we have an array of employees:
const employees = [
'Carol kristen deck ',
'john weber Smith',
'Alice k Johnson'
];
If we wanted to get the employee on index 1, we would do this:
employees[1]
But with destructuring, we can unpack the values into variables like this:
const employees = [
"Carol kristen deck ",
"john weber Smith",
"Alice k Johnson",
];
const [E1,E2,E3 ] = employees;
E1 will be the value of the first employee of the array, E2 is the value of the second employee and so on; if you just want the first employees of the array, you can commit the rest like this:
const [E1, ,] = employees;
console.log(E1);
// Carol kristen deck
Object Literals
Object literals allow developers to avoid duplication when writing objects. For example, suppose we have a Task function constructor that looks like this:
function Task(title, description, priority) {
return {
title: title,
description: description,
priority: priority
};
}
With ES6 object literals, you can write the short hand version like this;
function Task(title, description, priority) {
return {
title,
description,
priority,
};
}
The Spread Operator
The spread operator is used to spread elements of iterable objects. Iterable objects include arrays, objects, and strings.
The spread operator can copy, combine, or pass elements as arguments to another function. For example, when you are working with arrays and you don’t want to alter the original array, you can use the spread operator to make a copy of the array like this:
const names = ["Alice", "Bob", "Charlie", "Diana", "Ethan"];
const namesCopy = [...names]
console.log(namesCopy)
The rest Operator
The rest operator is similar to the spread operator in that it uses three(…
) dots. However, the rest operator is used within function parameters to collect multiple arguments into a single array.
For example, suppose we need to create a function that gets the sum of numbers. Assuming our array takes an indefinite number of arguments, we can use the rest operator to collect the arguments into an array.
function sumNumbers(...arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
Then, we can use the function to handle any number of arguments.
numbers = [1, 2, 4];
grades = [30, 40, 50, 60, 70];
console.log(sumNumbers(...numbers)); //output //7
console.log(sumNumbers(...grades)); //output //250
The rest operator can also be used in restructuring assignments. For example, suppose, we need to extract the first element of the grades array, we can extract it into a variable and then collect the rest of the elements into an array as shown below.
grades = [30, 40, 50, 60, 70];
const [index0, ...arr] = grades;
console.log(math);
The for of loop
The for of loop is used to iterate elements in iterable objects such as arrays, strings, typed arrays, maps, sets, and NodeLists. The syntax of a for of loop looks like this:
for (variable of iterable) {
//code to be executed for each variable
}
Iterating over an Array
const currencyCodes = ["USD", "EUR", "GBP", "JPY"];
for (const code of currencyCodes) {
console.log(code);
}
// USD
// EUR
// GBP
// JPY
Iterating over an array of objects
For example, suppose we have an array containing several objects, as shown below.
const currencies = [
{ currency: "US Dollar", code: "USD" },
{ currency: "Euro", code: "EUR" },
{ currency: "British Pound", code: "GBP" },
{ currency: "Japanese Yen", code: "JPY" }
];
If we iterate over the currencies array, we will get each individual object.
for (const currency of currencies) {
console.log(currency);
}
The output will look like this:
{ currency: 'US Dollar', code: 'USD' }
{ currency: 'Euro', code: 'EUR' }
{ currency: 'British Pound', code: 'GBP' }
{ currency: 'Japanese Yen', code: 'JPY' }
Iterating over a NodeList
A NodeList is a collection of nodes extracted from the document of a web page. For example, suppose you have a <ul>
of <li>
elements in our page :
<ul class="languages">
<li>Python</li>
<li>JavaScript</li>
<li>Ruby</li>
</ul>
We can use the querySelectorAll attribute to get the NodeList containing the
const listItems = document.querySelectorAll('.languages li')
Then use the for of loop concept to get the textContent of each
const listItems = document.querySelectorAll(".languages li");
for (const item of listItems) {
console.log(item.textContent);
}
Conclusion
Which ES6 Features do you find yourself using almost every day? Let me know in the comments below.
Thanks for reading
The best way to master JavaScript is by building projects. Subscribe to the Practical JavaScript Newsletter and level up your JavaScript skills.