Learn ECMAScript 2015 (ES6) Features: Let, Arrow Functions, Classes, and more!
The version that was embraced by devs with love!
Table of contents
No headings in the article.
In the previous article, we gained an understanding of ECMA and its evolving nature with each version. In this second article of the series, we will delve deeper into ECMAScript 2015 (ES6) and explore its new features. By the end of this article, you will have a clear understanding of the key features introduced in ES6, along with practical examples that demonstrate their usage. With this knowledge, you can confidently leverage these features in your daily tasks.
let and const keyword
In JavaScript, we have three keywords for declaring variables: var, let, and const. While var declares variables with global scope, let and const are block-scoped. This means that variables declared with let or const are only accessible within the block of code where they were defined, while variables declared with var are accessible throughout the entire program.
The main difference between let and const is that const variables are immutable, meaning their value cannot be changed once they are assigned. On the other hand, variables declared with let can be reassigned with a new value. Understanding the differences between these keywords is important for writing efficient and bug-free code in JavaScript.
var name = "Coding"; console.log(name); // will print "Coding" { let name = "Moon"; console.log(name); // will print "Moon" } { const greet = "Hello"; console.log(greet); // will print "Hello" greet = "World"; // will through error }
Arrow Functions
Arrow functions are a modern and elegant way to write functions in JavaScript. They offer a concise and readable syntax, making code more structured and enjoyable to write. With their ability to capture the 'this' value of the enclosing context, arrow functions also offer more predictability compared to traditional function expressions.
// OLD WAY function sayHello(name){ console.log("Hello ",name); } sayHello("Moon"); // output - // Hello Moon //-------------------------------- // NEW WAY const sayHello = (name) => { console.log("Hi ",name); } sayHello("Moon"); // output - // Hi Moon
The spread (...) Operator
The ... operator is used to expand an iterable.
let listOne = ["water","pen"]; let listTwo = ["coffee","notebook"]; const finalList = [ ...listOne, ...listTwo ]; console.log(finalList); // ["water","pen","coffee","notebook"]
For/of
For/of is used to iterate over an iterable object like an array, string, map, set, etc.
In this, we don't have to increment the index as we do in the traditional old for loop. And we can use any type of variable (var/let/const) to assign the value of the property(In the below example we have `const element`).
const words = ['hello', 'world', 'bye']; for (const element of words) { console.log(element); } // Expected output: // "hello" // "world" // "bye"
Map Objects
Map consists of key and value pair. The key-value are stored in a Map in the order they are inserted and it has many methods and size properties.
You can read this detailed article on Maps here -> Map (developer.mozilla)Set Objects
The set is similar to an array but holds only a unique value i.e. there will be no value twice in the set. It has many methods and size properties.
You can read this detailed article on Sets here -> Set (developer.mozilla)
Classes
Classes are templates for objects. This means we can create classes with the constructor method and declare properties, then use it to create an Object that will have the same properties
class User { constructor(name, age) { this.name = name; this.age = age; } } // using class const user1 = new User("Om", 27); console.log(user1.name); // Om const user2 = new User("Rahul", 29); console.log(user2.age); // 29
Promises
The Promise object in JavaScript allows developers to work with asynchronous code in a more structured and predictable way. A promise object contains both the code that generates results and the code that will consume those results. Promises have two important properties: state and result.
When the promise generates a result, one of two callbacks is called depending on the result: resolve or reject. This allows developers to handle success and error cases separately and with more precision, resulting in cleaner and more maintainable code.
You can read the detailed article on Promise here -> Promise (w3schools)
Symbol
It is a special primitive data type that is unique and hidden. It is used to create a unique identifier.
const user = { name: "Ben Carp", age: 24, pronouns: "he/his/him" }; let user = Symbol('uid'); user[uid] = 22002; // Now user[uid] = 22002 // but user.uid is still undefined
Default Parameters
If no parameter is passed and we want it to be something else than undefined then we use a default value like this -
const greet = (name = "Guest") => { console.log("Hello ", name); } greet("CodingMoon"); // Hello CodingMoon greet(); // Hello Guest
Rest Parameter (...)
It is used to get the remaining argument of an array or an object.
const users = ["Dev","Abhinav","Ronit","Shaurya","Simar"]; const [user1, user2, ...remainingUser] = users; console.log(user1); // Dev console.log(user2); // Abhinav console.log(remainingUser); // ["Ronit","Shaurya","Simar"]
String.includes()
The includes() method returns true if the string contains a specific value
const quote = "Honesty is the best policy"; quote.includes("best"); // true quote.includes("hardwork"); // false
String.startsWith()
The startsWith() method returns true if the string begins with a specific value
const quote = "Honesty is the best policy"; quote.includes("Honesty"); // true quote.includes("best"); // false
String.endsWith()
The endsWith() method returns true if the string ends with a specific value
const quote = "Honesty is the best policy"; quote.includes("policy"); // true quote.includes("best"); // false
Array.from()
The Array.from() method returns an Array object from any Object that has length property or is iterable.
Array.from("XYZ") // Returns [X,Y,Z]
Array find()
The find() method takes the function as a parameter and returns the value of the first array element that the function returns true for.
const checkFunction = (value) => { return value > 5; } const numbers = [2,6,9,10,5]; let result = numbers.find(checkFunction); // result will be -> 6
Array findIndex()
The findIndex() method takes the function as a parameter and returns the index of the first array element that the function returns true for.
const checkFunction = (value) => { return value > 5; } const numbers = [2,6,9,10,5]; let result = numbers.findIndex(checkFunction); // result will be -> 1
Math and Number
Math and Number has static properties and methods to perform Mathematical stuff. You can read about all the methods and properties here ->
New Global Methods
Two new global methods added in ES6 are -
isFinite() - return false if the argument is infinite or NaN(Not A Number) else true
isFinite(1/0); // returns false isFinite(1); // returns true
isNan() - returns true if the argument is NaN(Not A Number) else false
isNaN("Magic"); // returns true
In conclusion, ECMAScript 2015 (ES6) introduced a lot of new features and enhancements to JavaScript, which made it easier and more efficient for developers to write complex code. In this article, we have discussed some of the most useful features of ES6.
By incorporating these features into your code, you can improve the readability, maintainability, and performance of your JavaScript applications. It's important to stay up-to-date with the latest advancements in the language to make the most of its capabilities and achieve better results in your projects.
I will post more articles in the Ecma Script series soon. Thanks for your time ๐