Learn ECMAScript 2015 (ES6) Features: Let, Arrow Functions, Classes, and more!

Learn ECMAScript 2015 (ES6) Features: Let, Arrow Functions, Classes, and more!

The version that was embraced by devs with love!

ยท

6 min read

Table of contents

No heading

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.

  1. 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
     }
    
  2. 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
    
  3. 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"]
    
  4. 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"
    
  5. 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)

  6. 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)

  7. 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
    
  8. 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)

  9. 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
    
  10. 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
    
  11. 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"]
    
  12. 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
    
  13. 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
    
  14. 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
    
  15. 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]
    
  16. 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
    
  17. 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
    
  18. 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 ->

    1. Math (developer.mozilla)

    2. Number (developer.mozilla)

  19. New Global Methods

    Two new global methods added in ES6 are -

    1. isFinite() - return false if the argument is infinite or NaN(Not A Number) else true

       isFinite(1/0);       // returns false
       isFinite(1);       // returns true
      
    2. 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 ๐Ÿ˜

Did you find this article valuable?

Support Mayank Sahai by becoming a sponsor. Any amount is appreciated!

ย