JavaScript ES6 Features You need to Know before Learning React
Tags: react, beginners, javascript
Published: 2024-06-06 11:38:43

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.

```js
// 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
```js
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.

```js
// 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.

```js
// 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

```js
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.

```js
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:
```js
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:

```js
const { catNname, age, color, breed } = cat;
console.log(`My cat ${catNname} is ${age} moths old`)
```
The output will be:
```sh
My cat Whiskers is 3 months old
```

## Destructuring Arrays
Destructuring arrays is similar to Destructuring objects;. Suppose we have an array of employees:
```js
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:
```js
employees[1]
```
But with destructuring, we can unpack the values into variables like this:
```js
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:

```js
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:

```js
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;

```js
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:

```js
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.

```js
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.

```js
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.
```js
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:
```js
for (variable of iterable) {
  //code to be executed for each variable
}
```
### Iterating over an Array
```js
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.
```js
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.

```js
for (const currency of currencies) {
  console.log(currency);
}
```

The output will look like this:

```js
{ 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 :

```html
<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 <li> elements like this
```js
 const listItems = document.querySelectorAll('.languages li')
```
Then use the for of loop concept to get the textContent of each <li> element

```js
const listItems = document.querySelectorAll(".languages li");
for (const item of listItems) {
  console.log(item.textContent);
}
```

![nodelist](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4e7cvrels6w1dlpfkfal.png)

## 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.](https://practicaljavascript.substack.com/)