Features of ES6 JavaScript
Learn about the key ES6 features utilized in React development
We'll cover the following...
Destructuring
The word "destructuring" is an awkward word to say and maybe we can't even find it in the dictionary. However, you might have used this feature quite a few times in the past:
const arr = [1, 2, 3]const [a, b] = arr
Essentially, destructuring allows you to destruct an object and assign the dissembled elements to variables. The preceding code is destructuring usage applied to an array, which is equivalent to the following:
const a = arr[0]const b = arr[1]
You can see that during the destructuring process, we follow the given structure to select the needed elements. Similarly, it can be applied to an object:
const name = { first: 'John', last: 'Doe' }const { first, last } = name
The preceding statement translates to the following:
const first = name.firstconst last = name.last
Although we can continue to use the old method, destructuring is much easier and quicker to use. Keep in mind that the element you select has to exist; otherwise, you can get an undefined
, as shown in the following case:
const name = { first: 'John' }const { second } = name
Another useful feature with destructuring is that you can rename a property if you want to store it under another name:
const { first: firstName } = name
The preceding line translates to the following:
const firstName = name.first
Essentially, the firstName
variable is used for the assignment instead of first
, even though first
is the property name under the object.
Quite often, destructuring is used in combination with other ES6 features, such as the spread operator:
const { first } = { ...name, last }
We see this preceding statement quite often in the React code, so let's discuss each part of it:
...name
is to spread all properties of thename
object....