Things You Need To Know About ES6 If You Want To Be A Good ReactJS Developer

ES6 stands for ECMAScript 6. ECMAScript was created to standardize JavaScript, and ES6 is the 6th version of ECMAScript, it was published in 2015, and is also known as ECMAScript 2015.

Why you should learn ES6.

React uses ES6, and you should be familiar with some new features, like:

  • Classes

  • Arrow Functions

  • Variables (let, const, var)

  • Array Methods like .map()

  • Destructuring

  • Modules

  • Ternary Operator

  • Spread Operator

Let's start explaining the features above one after the other:

Classes:

A class is a type of function, but instead of using the keyword function to initiate it, we use the keyword class, and the properties are assigned inside a constructor() method. ES6 introduced classes.

Example:

class House {
  constructor(name) {
    this.location = name;
  }
}

Notice the case of the class name. We have begun the name, "House", with an uppercase character. This is a standard naming convention for classes. Now let us create objects using the class:

class House {
  constructor(name) {
    this.location = name;
  }
}

const myhouse = new House("Mansion");

Note: The constructor function is called automatically when the object is initialized.

Now add a method by creating a method named present() in the class:

class House {
  constructor(name) {
    this.location = name;
  }

  present() {
    return 'I have a  house in ' + this.location;
  }
}

const myhouse = new House("Quebec");
myhouse.present();

As you can see in the example above, you call the method by referring to the object's method name followed by parentheses (parameters would go inside the parentheses).

Now let's create a class inheritance. To create a class inheritance, use the extends keyword.

A class created with a class inheritance inherits all the methods from another class:

class House {
  constructor(name) {
    this.location = name;
  }

  present() {
    return 'I have a house at ' + this.location;
  }
}

class Color extends House {
  constructor(name, col) {
    super(name);
    this.color = col;
  }  
  show() {
      return this.present() + ', it is ' + this.color
  }
}
const myhouse = new Color("Blue", "Green");
myhouse.show();

The super() method refers to the parent class. By calling the super() method in the constructor method, we call the parent's constructor method and gets access to the parent's properties and methods.

Arrow Functions:

Arrow functions allow us to write shorter function syntax.

Example:

hello = () => {
  return "Hello World!";
}

Without arrow function, it can be written like this:

hello = function() {
  return "Hello World!";
}

The two examples above still mean the same thing, but we use arrow function in the first example, then used regular function in the second example. Using the arrow function makes it gets shorter! If the function has only one statement, and the statement returns a value, you can remove the brackets and the return keyword.

Example:

hello = () => "Hello World!";

Note: This works only if the function has only one statement.

If you have parameters, you pass them inside the parentheses.

Example:

hello = (val) => "Hello " + val;

Note that if you have only one parameter, you can skip the parentheses as well.

Example:

hello = val => "Hello " + val;

What About this?

The handling of this is also different in arrow functions compared to regular functions. In short, with arrow functions, there are no binding of this.

In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever.

With arrow functions, the this keyword always represents the object that defined the arrow function.

Let us take a look at two examples to understand the difference.

Both examples call a method twice, first when the page loads, and once again when the user clicks a button.

The first example uses a regular function, and the second example uses an arrow function.

The result shows that the first example returns two different objects (window and button), and the second example returns the Header object twice.

First example using regular function. With a regular function, this represents the object that called the function:

class Header {
  constructor() {
    this.color = "Blue";
  }

//Regular function:
  changeColor = function() {
    document.getElementById("demo").innerHTML += this;
  }
}

const myheader = new Header();

//The window object calls the function:
window.addEventListener("load", myheader.changeColor);

//A button object calls the function:
document.getElementById("btn").addEventListener("click", myheader.changeColor);

Lastly, the second example that use the arrow function. With an arrow function, this represents the Header object, no matter who called the function:

class Header {
  constructor() {
    this.color = "Blue";
  }

//Arrow function:
  changeColor = () => {
    document.getElementById("demo").innerHTML += this;
  }
}

const myheader = new Header();


//The window object calls the function:
window.addEventListener("load", myheader.changeColor);

//A button object calls the function:
document.getElementById("btn").addEventListener("click", myheader.changeColor);

Note: Remember these differences when you are working with functions. Sometimes the behavior of regular functions is what you want, if not, use arrow functions.

Variables (let, const, var)

With ES6, there are three ways of defining your variables: var, let, and const. Before ES6, there were only one way of defining your variables: with the var keyword. If you did not define them, they would be assigned to the global object. Unless you were in strict mode, then you would get an error if your variables were undefined.

Example:

var x = 5.6;

If you use var outside a function, it belongs to the global scope.

If you use var inside a function, it belongs to that function.

Also, If you use var inside a block, i.e. a for loop, the variable is still available outside that block.

Note: var has a function scope, not a block scope.

let:

let Is the block scoped version of var, and is limited to the block (or expression) where it is defined. If you use let inside a block, i.e. a for loop, the variable is only available inside that loop.

Note: let has a block scope.

Example:

let x = 5.6;

const:

const is a variable that once it has been created, its value can never change.

The keyword const is a bit misleading.

Note: It does not define a constant value. It defines a constant reference to a value.

Because of this, you cannot:

  • Reassign a constant value

  • Reassign a constant array

  • Reassign a constant object

But you can do this:

  • Change the elements of constant array

  • Change the properties of constant object

Array Methods

There are many JavaScript array methods. But, the one of the most useful in React is the .map() array method. The .map() method allows you to run a function on each item in the array, returning a new array as the result. In React, map() can be used to generate lists.

Code Sample:

const myArray = ['apple', 'banana', 'orange'];

const myList = myArray.map((item) => <p>{item}</p>)

Destructuring

Destructuring makes it easy to extract only what is needed. Destructuring is exactly the same. We may have an array or object that we are working with, but we only require some items contained in these.

Old way of assigning array items to a variable:

const vehicles = ['mustang', 'f-150', 'expedition'];

// old way
const car = vehicles[0];
const truck = vehicles[1];
const suv = vehicles[2];

New way of assigning array items to a variable:

const vehicles = ['mustang', 'f-150', 'expedition'];

const [car, truck, suv] = vehicles;

Note: When destructuring arrays, the order that variables are declared is important.

The sample below only show that we only want the car and suv we can simply leave out the truck but keep the comma.

Code Sample:

const vehicles = ['mustang', 'f-150', 'expedition'];

const [car,, suv] = vehicles;

Destructuring comes in handy when a function returns an array.

Code Sample:

<!DOCTYPE html>
<html>

<body>

<script>
function calculate(a, b) {
  const add = a + b;
  const subtract = a - b;
  const multiply = a * b;
  const divide = a / b;

  return [add, subtract, multiply, divide];
}

const [add, subtract, multiply, divide] = calculate(4, 7);

document.write("<p>Sum: " + add + "</p>");
document.write("<p>Difference " + subtract + "</p>");
document.write("<p>Product: " + multiply + "</p>");
document.write("<p>Quotient " + divide + "</p>");
</script>

</body>
</html>

Now let give example of how to destructure an object inside function:

<!DOCTYPE html>
<html>

<body>

<p id="demo"></p>

<script>
const vehicleOne = {
  brand: 'Ford',
  model: 'Mustang',
  type: 'car',
  year: 2021, 
  color: 'red'
}

myVehicle(vehicleOne);

function myVehicle({type, color, brand, model}) {
  const message = 'My ' + type + ' is a ' + color + ' ' + brand + ' ' + model + '.';

  document.getElementById("demo").innerHTML = message;
}
</script>

</body>
</html>

Note: The object properties do not have to be declared in a specific order.

We can also destructure deeply nested objects by referencing the nested object then using a colon and curly braces to again destructure the items needed from the nested object.

Example:

<!DOCTYPE html>
<html>

<body>

<p id="demo"></p>

<script>
const vehicleOne = {
  brand: 'Ford',
  model: 'Mustang',
  type: 'car',
  year: 2021, 
  color: 'red',
  registration: {
    city: 'Houston',
    state: 'Texas',
    country: 'USA'
  }
}

myVehicle(vehicleOne)

function myVehicle({ model, registration: { state } }) {
  const message = 'My ' + model + ' is registered in ' + state + '.';

  document.getElementById("demo").innerHTML = message;
}
</script>

</body>
</html>

Spread Operator

The JavaScript spread operator (...) allows us to quickly copy all or part of an existing array or object into another array or object.

Example:

<!DOCTYPE html>
<html>

<body>

<script>
const numbersOne = [1, 2, 3];
const numbersTwo = [4, 5, 6];
const numbersCombined = [...numbersOne, ...numbersTwo];

document.write(numbersCombined);
</script>

</body>
</html>

Most time the spread operator is used in combination with destructuring.

Example:

<!DOCTYPE html>
<html>

<body>

<script>
const numbers = [1, 2, 3, 4, 5, 6];

const [one, two, ...rest] = numbers;

document.write("<p>" + one + "</p>");
document.write("<p>" + two + "</p>");
document.write("<p>" + rest + "</p>");
</script>

</body>
</html>

In the code above we assign the first and second items from numbers to variables and put the rest in an array.

We can also use the spread operator with objects.

Example:

<!DOCTYPE html>
<html>

<body>

<script>
const myVehicle = {
  brand: 'Ford',
  model: 'Mustang',
  color: 'red'
}

const updateMyVehicle = {
  type: 'car',
  year: 2021, 
  color: 'yellow'
}

const myUpdatedVehicle = {...myVehicle, ...updateMyVehicle}
</script>

</body>
</html>

You will notice that, the properties that did not match were combined, but the property that did match, color, was overwritten by the last object that was passed, updateMyVehicle. The resulting color is now yellow.

Modules

JavaScript modules allow you to break up your code into separate files. ES Modules rely on the import and export statements.

Export

You can export a function or variable from any file. Let us create a file named person.js, and fill it with the things we want to export.

Note: There are two types of exports: Named and Default.

You can use export in-line individually:

export const name = "Jesse"
export const age = 40

You can also use it at once:

const name = "Jesse"
const age = 40

export { name, age }

Default Exports

Let us create another file, named message.js, and use it for demonstrating default export.

Note: You can only have one default export in a file.

Example:

const message = () => {
  const name = "Jesse";
  const age = 40;
  return name + ' is ' + age + 'years old.';
};

export default message;

Import

You can import modules into a file in two ways, based on if they are named exports or default exports.

Named exports must be destructured using curly braces. But Default exports do not.

Import from named exports code sample:

import { name, age } from "./person.js";

Import from default exports code sample:

import message from "./message.js";

Ternary Operator

The ternary operator is a simplified conditional operator like if / else.

Syntax: condition ? <expression if true> : <expression if false>

Code sample using if / else statement without ternary:

if (authenticated) {
  renderApp();
} else {
  renderLogin();
}

Here is the same sample using the ternary operator:

authenticated ? renderApp() : renderLogin();

I believe you now have some basic knowlegde about JavaScript ES6.

Thanks for reading.

Happy Coding!

Never give up on your goals. Always remember that those Senior Software Developers are once Junior Software Developers. Everything in life is a stage. Don't give up on the process. Stay Strong, and also stay focus. You will surely be proud of yourself someday....

Check this ads to explore

Did you find this article valuable?

Support Saint Vandora by becoming a sponsor. Any amount is appreciated!