Today, we will dive into eight useful and interesting ECMAScript 6 (ES2015) features, like classes, to help developers familiar with object-oriented programming get started with JavaScript.
We will also explore typical features inspired by functional programming languages, such as arrow functions and let variables.
1. Using const and let
After years of using the keyword var to create variables and instantiate objects, ES6 added two new keywords to handle variables: const and let.
They are important features, and it’s highly recommended to use them instead of the old var to avoid hoisting problems.
The main difference between const and let is that const creates constants, while let works like var but avoids hoisting problems.
As a best practice, always use const to handle immutable data, because it uses less memory than using let. Take a look at this example:
// creating a constant
const MAX = 10;
// creating a variable
let value = 5;
// you can't change the value of a constant
MAX = 5;
// this change is allowed for `let` variables
value = 10;
// creating a constant object
const obj = {};
// You can only change object's attribute
obj.a = 10;
// but you can't reassign new data here
obj = 100;
2. Template Strings
The template string is a powerful feature that allows you to interpolate data inside a string in an elegant way.
To create a template string, use backticks, like this: This is a template string. If you need to interpolate data inside a string, you just need to use this syntax: ${data}. Take a look at the example below:
var name = "John Connor";
console.log(`This is ${name} from the future!`);
Another advantage of using template strings is to write multiline strings without concatenating strings using the + operator; now you can just break a line to do it:
var template = `
<div>
<p>This is multline string</p>
</div>
`;
3. Arrow Functions
In JavaScript, it is very common to invoke functions, anonymous functions, and callback functions using the keyword function.
Arrow functions are a new feature that changes how we create functions and how they behave. Using the syntax sugar => creates a function that doesn’t require the keyword function and doesn’t create special variables like arguments. See some arrow examples:
// empty arrow-function
const foo() => {};
// inline arrow-function
const add = (a, b) => {
a + b
};
// arrow-function
const compare = (a, b) => {
if (a > b) {
return a;
} else {
return b;
}
};
// arrow-function sharing context
const doSomething = (a, b) => {
this.a = a;
// there is no need to use parenthesis when there is one argument
const doNewThing = b => {
this.b = b;
return this.a + this.b;
}
}
4. Spread Operators
The Spread Operator basically converts an array into arguments, it is very useful when you need to break array values to send them as parameters for a function or object constructors.
To understand these features, first, let’s create a simple function below:
function add(a, b) => {
return a + b
};
Now, to invoke this function using an array of elements as arguments, you just need to use this syntax: …array. Take a look:
const values = [1, 2];
add(...values); // returns 3
5. Method Definition
If you need to create simple objects with some attributes and some functions, ES6 makes the process easier, for example:
var MyObject = {
a: 1,
inc: function(b) {
this.a += b;
}
}
You can create methods instead of object functions, eliminating the use of function keywords; have a look:
var MyObject = {
a: 1,
// syntax sugar to create methods
inc(b) {
this.a += b;
}
}
6. Classes and inheritances
Classes are one of the most anticipated ES6 features. Now you can create a class without directly using prototype objects in JavaScript.
While using classes, you can include constructors, destructors, methods, and inheritance.
To see the differences between classes and prototype objects, we’re going to write the same Vehicle object using class and prototype. First, take a look at how we can create a Vehicle prototype object:
var Vehicle = function(name) {
this.name = name;
}
Vehicle.prototype.drive = function() {
console.log("Driving the ", this.name);
};
And now, we can write an expressive Vehicle object using the ES6 class feature; see this example below:
class Vehicle {
constructor(name) {
this.name = name;
}
drive() {
console.log("Driving the ", this.name);
}
}
Using classes, your code will be more expressive and cleaner. And what if we need to use inheritance? Using OOP*(Object-Oriented Programming)* concepts, let’s create a Car class that extends the Vehicle class.
To do this, use the keyword extends to set the parent class. In the child class constructor, you can use the super() method to call the parent class constructor when the current class is instantiated. See this example:
class Car extends Vehicle {
constructor(name, brand) {
super(name);
this.brand = brand;
}
}
There is no new way to instantiate a class because it follows the same way you instantiate prototype objects too, so nothing is changed in the code below:
let car = new Car("A3", "Audi");
car.drive();
7. Default arguments
Default arguments are a long-standing feature, used in languages like Ruby, Python, PHP, and Java. Basically, it sets a default value for function arguments when these arguments do not have a value during a function invocation. In ES5, it was very normal to do this:
function Person(name, age) {
this.name = name || " John";
this.age = age || 25;
}
It was very common to use the OR operator to simulate default values for these arguments. Now you can write less complex code using the default arguments:
function Person(name = "John", age = 25) {
this.name = name;
this.age = age;
}
8. Object destructuring assignment
The shorthand value feature allows you to write less code when an object key and variable have the same name, for example:
// Creating a const name from this.obj.name
const {
name
} = this.obj;
// This is the same as writing: const name = this.obj.name;
You can apply destructuring when you create a new object as well:
const name = "John Connor";
const obj = {
name
} // This is the same of write: obj = { name: name }
Final Thoughts
In this post, you learned a few useful features from ES6 (ECMAScript 6).
Today, not all features are compatible with the main browsers; even the latest version of Node.js still isn’t. To solve this problem, you can use Babel, which falls back all main ES6 features to compatible ES5 for old browsers and Node.js too by transpiling the code.
Moreover, if you want to learn more about new JavaScript features and how to use Babel to run your application everywhere, check out our post.