What is ES6? Part-5
ES6 or the ECMAScript 2015 is the 6th and major edition of the ECMAScript language specification standard. It defines the standard for the implementation of JavaScript and it has become much more popular than the previous edition ES5.
ES6 comes with significant changes to the JavaScript language. It brought several new features like, let and const keywords, rest and spread operators, template literals, classes, modules and many other enhancements to make JavaScript programming easier and more fun. In this article, we will discuss some of the best and most popular ES6 features that we can use in your everyday JavaScript coding.
let and const Keywords
Arrow Functions
Multi-line Strings
Default Parameters
Template Literals
Destructuring Assignment
Enhanced Object Literals
Promises
Classes
Modules
Understanding these Features
1. let and const keywords :
The keyword "let" enables the users to define variables and on the other hand, "const" enables the users to define constants. Variables were previously declared using "var" which had function scope and were hoisted to the top. It means that a variable can be used before declaration. But, the "let" variables and constants have block scope which is surrounded by curly braces "{}" and cannot be used before declaration.
let i = 10;
console.log(i); //Output 10
const PI = 3.14;
console.log(PI); //Output 3.14
Scope determines the accessibility (visibility) of variables.
JavaScript has 3 types of scope:
Block scope
Function scope
Global scope
2. Arrow Functions
ES6 provides a feature known as Arrow Functions. It provides a more concise syntax for writing function expressions by removing the "function" and "return" keywords.
Arrow functions are defined using the fat arrow (=>
) notation.
// Arrow function
let sumOfTwoNumbers = (a, b) => a + b;
console.log(sum(10, 20)); // Output 30
There is no "return" or "function" keyword in the arrow function declaration.
We can also skip the parenthesis in the case when there is exactly one parameter, but will always need to use it when you have zero or more than one parameter.
But, if there are multiple expressions in the function body, then we need to wrap it with curly braces ("{}"). We also need to use the "return" statement to return the required value.
3. Multi-line Strings
ES6 also provides Multi-line Strings. Users can create multi-line strings by using back-ticks(`).
It can be done as shown below :
let greeting = `Hello World,
Greetings to all,
Keep Learning and Practicing!`
4. Default Parameters
In ES6, users can provide the default values right in the signature of the functions. But, in ES5, the OR operator had to be used.
//ES6
let calculateArea = function(height = 100, width = 50) {
// logic
}
//ES5
var calculateArea = function(height, width) {
height = height || 50;
width = width || 80;
// logic
}
5. Template Literals
ES6 introduces very simple string templates along with placeholders for the variables. The syntax for using the string template is ${PARAMETER} and is used inside of the back-ticked string.
let name = `My name is ${firstName} ${lastName}`
6. Destructuring Assignment
Destructuring is one of the most popular features of ES6. The destructuring assignment is an expression that makes it easy to extract values from arrays, or properties from objects, into distinct variables.
There are two types of destructuring assignment expressions, namely, Array Destructuring and Object Destructuring. It can be used in the following manner :
//Array Destructuring
let fruits = ["Apple", "Banana"];
let [a, b] = fruits; // Array destructuring assignment
console.log(a, b);
//Object Destructuring
let person = {name: "Peter", age: 28};
let {name, age} = person; // Object destructuring assignment
console.log(name, age);
7. Enhanced Object Literal
ES6 provides enhanced object literals which make it easy to quickly create objects with properties inside the curly braces.
function getMobile(manufacturer, model, year) {
return {
manufacturer,
model,
year
}
}
getMobile("Samsung", "Galaxy", "2020");
8. Promises
In ES6, Promises are used for asynchronous execution. We can use promise with the arrow function as demonstrated below.
var asyncCall = new Promise((resolve, reject) => {
// do something
resolve();
}).then(()=> {
console.log('DON!');
})
9. Modules
Previously, there was no native support for modules in JavaScript. ES6 introduced a new feature called modules, in which each module is represented by a separate ".js" file. We can use the "import" or "export" statement in a module to import or export variables, functions, classes or any other component from/to different files and modules.
export var num = 50;
export function getName(fullName) {
//data
};
import {num, getName} from 'module';
console.log(num); // 50
10. Classes
Previously, classes never existed in JavaScript. Classes are introduced in ES6 which looks similar to classes in other object-oriented languages, such as C++, Java, PHP, etc. But, they do not work exactly the same way. ES6 classes make it simpler to create objects, implement inheritance by using the "extends" keyword and also reuse the code efficiently.
In ES6, we can declare a class using the new "class" keyword followed by the name of the class.
A class definition
This is how a class looks.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
}
// Example usage
const person1 = new Person("Alice", 25);
person1.greet();
Here's a step-by-step approach to JavaScript classes:
1. Introduction to Object-Oriented Programming: The concept of Object-Oriented Programming (OOP). Define key terms such as classes, objects, properties, and methods. OOP promotes modularity and reusability in programming.
2. What are Classes and Objects: Classes are like blueprints or templates for creating objects. Objects are instances of a class and contain both data (properties) and functions (methods).
3. Creating a Class: How to define a class in JavaScript using the class
keyword. The syntax for declaring properties and methods within a class. Here's a basic example:
codeclass Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
}
4. Creating Objects from a Class: Demonstrate how to create objects (instances) from a class using the new
keyword. Emphasize that each object has its own set of properties and methods, but they share the same structure defined by the class.
const person1 = new Person("Alice", 25);
const person2 = new Person("Bob", 30);
person1.greet(); // Output: Hello, my name is Alice and I'm 25 years old.
person2.greet(); // Output: Hello, my name is Bob and I'm 30 years old.
Class inheritance
A class can extend another class, and objects initialized using that class inherit all the methods of both classes.
If the inherited class has a method with the same name as one of the classes higher in the hierarchy, the closest method takes precedence:
class Programmer extends Person {
hello() {
return super.hello() + ' I am a programmer.'
}
}
const flavio = new Programmer('Flavio')
flavio.hello()
(the above program prints “Hello, I am Flavio. I am a programmer.”)
Classes do not have explicit class variable declarations, but you must initialize any variable in the constructor.
Inside a class, you can reference the parent class calling super()
.
Static methods
Normally methods are defined on the instance, not on the class.
Static methods are executed on the class instead:
class Person {
static genericHello() {
return 'Hello'
}
}
Person.genericHello() //Hello
Private methods
JavaScript does not have a built-in way to define private or protected methods.
There are workarounds, but I won’t describe them here.
Getters and setters
You can add methods prefixed with get
or set
to create a getter and setter, which are two different pieces of code that are executed based on what you are doing: accessing the variable, or modifying its value.
class Person {
constructor(name) {
this._name = name
}
set name(value) {
this._name = value
}
get name() {
return this._name
}
}
If you only have a getter, the property cannot be set, and any attempt at doing so will be ignored:
class Person {
constructor(name) {
this._name = name
}
get name() {
return this._name
}
}
If you only have a setter, you can change the value but not access it from the outside:
class Person {
constructor(name) {
this._name = name
}
set name(value) {
this._name = value
}
}
class UserProfile {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
getName() {
console.log(`The Full-Name is ${this.firstName} ${this.lastName}`);
}
}
let obj = new UserProfile('John', 'Smith');
obj.getName(); // output: The Full-Name is John Smith
Summary
In this article, we learned about the ECMAScript 2015 or ES6, which defines the standard for JavaScript implementation.
We also learned about the top 10 features of ES6 which makes it very popular.
ES6 provides classes, modules, arrow functions, template literals, destructuring assignments and many more features which make working with JavaScript a lot easier.