React – ES6

ES6 is short for ECMAScript 2015, which is a major version of the javascript release. It has brought exciting new features, syntax, and methods to the JavaScript language. The ES6 syntax gives you more flexibility and productive ways of writing code.

It is highly used together with React and is widely supported in modern browsers like Chrome and Firefox. We will learn different ES6 features in the subsequent sections.

Although there are more versions of ES, such as ES7, ES8, ES9, ES6 is the most prominent release and significant one.

Variable Declaration

Previously in JavaScript, variables were declared using the var keyword. Now, we have two new keywords for declaring variables, let and const, in addition to var.

Try to avoid var as much as possible. The reason is that let and const follow something called lexical scoping, which is very important. Lexical scoping means the variable you declare will only be available inside the nearest containing block.

Notable Features –

  • “let” declares a variable that can be changed at a later point in your program.
let name = 'John';
let phoneNumber = 123456789;
/* re-assignment such as: name = 'John Smith'; is allowed */
  • “const” declares a variable that you cannot change later once it’s assigned a value.
const name = 'John';
/* name = 'John Smith'; Not allowed as name is a constant */

Destructuring

Destructuring means breaking down the structure of an entity into its parts. We can access an object property or an array value with the destruct syntax and store it in a variable.

It removes the need for multiple assignments to variables; It is simply fast and a clean way.

There are two types of destructuring possible:

  • Object Destructuring
  • Array Destructuring

Object Destructuring

Declare the variables inside the curly braces { } that you want to destructure from the object. So if we have myObject as:

const myObject = {
    prop1: 'val1',
    prop2: 'val2'
}
// specify the object to destructure on the right hand side
const { prop1, prop2 } = myObject;
/* It is the same as doing:
  * const prop1 = myObject.prop1;
  * const prop2 = myObject.prop2;
  */

The variable name that you want to destructure must match the property name in that object. You can also assign some other name to the property using a colon:

const { prop1: otherName } = myObject
// same as const otherName = myObject.prop1

Array Destructuring

Arrays don’t have property names like objects but use the order/position of elements. Therefore, the destructuring syntax is a little different. To destructure an array, use square brackets [ ] after the variable declaration keyword (var/let/const). Inside those brackets, specify the variable names that you would like to destructure from the array.

const names = [ 'Mary', 'John', 'David', 'Larry', 'Robin' ]
// variable names don't matter but its position or order does
const [ first, second, third ] = names;
/* It is the same as:
    const first = names[0];
    const second = names[1];
    const third = names[2];
*/
You can also skip values with empty commas:
const [ user1, , , user4 ] = names;
/* It is the same as:
    const user1 = names[0];
    const user4 = names[3];
*/

Spread Operator (…)

This operator is used to access an array/object’s contents without the braces {} or brackets [].

  • When used with an array, it represents the array’s values without the square brackets [].
    So if –

    const array = [ 3, 4, 5 ];
    // …array will be 3, 4, 5
  • When used with an object, it represents the object’s properties and values without the curly braces {}.
    Therefore if,

    const obj = { prop1: 'val1', prop2: 'val2' };
    // …obj will be prop1: 'val1', prop2: 'val2'

To use the spread operator, specify three dots (…) before an array or object. The value returned will be the stripped-down version of the array/object without brackets [] or braces {}.

Using the Spread Operator

The spread operator’s value cannot be stored inside a variable as it does not represent any valid data type. Its value is valid and can only be used inside other arrays/objects.

It is commonly used to clone and reuse the values of an array/object.

You can shallow clone/copy the array values into another array using the spread operator as below:

const myArr = ['one', 'two'];
const clonedArr = […myArr];
// clonedArr is now a separate copy of myArr

You can also clone objects using the spread operator:

const obj = { prop1: 'value1' }
const clonedObj = { …obj }
// clonedObj is now a different object from obj with the same values.

Arrow Functions

They are a shorter and faster way of writing anonymous functions in JavaScript. Anonymous functions don’t have any name, so you will have to store the function as an expression in a variable to overcome this limitation.

The general syntax of an arrow function is:

(param1, param2, …) => { 
    // function body
}

The function keyword is not required with arrow functions. Also, the parenthesis () and the function body {} are separated by an arrow sign =>. The arrow function can be used when an anonymous function is needed.

Forms of arrow functions

An arrow function can take different forms depending on the required situation. They are mentioned below:

1. Functions with one parameter

If an arrow function takes only a single parameter, then the parenthesizes are optional.

const myFunc = parameter => {
    // the function body
}

The parenthesizes is required if the function takes:

  • None or empty parameters:
    => { }
  • Two or more parameters:
    (a, b, …) => { }

2. Functions with only a return statement

If there is a function whose only purpose is to return some value, then the braces { } can be omitted. The value after the arrow is returned on executing the function.

const myFunc = (param1, param2) => value
    // same as
const myFunc = (param1, param2) => {
return value;
}

The braces will be required if you want to include one or more statements inside the function body other than the return statement.

ES6 Modules

A module is a javascript file that can be shared and used inside other javascript files. It allows us to split the logic and code into separate files and keep the code structure clean.

It is used commonly to import different npm modules and code libraries in React.

1. Exporting Multiple Values from a Module

If you need to export multiple values, then you have to use the export keyword.

myfile.js

const add = (a, b) => a + b;
const someVariable = 'value'
export { add, someVariable }

When you export in this way, you can import in other JS files as:

import myImport from 'myfile.js';

Now you will have access to add and mul functions and use them as:

myImport.add(a, b) and myImport.someVariable

2. Exporting Default Value from a Module

When you export a default value from a module, you can import and directly use it without referencing the method or variable name with the dot notation.

myFile.js

const add = (a, b) => a + b;
export default add;

otherFile.js

import addFunc from 'myFile.js';
// addFunc(a, b) is same as add(a, b)

There can be only one export default in a module. If you use export default, you cannot use the former multiple export syntax.

Summary

ES6 brought a lot of changes and syntax updates. It changed the way we write JavaScript for good. Apart from the features we discussed, new ES6 built-in methods like map, filter, and reduce are very useful and often required.

Start incorporating the ES6 syntax today in your React code until it becomes your new good habit.

Back to: React Tutorial > Learn React

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.