Mastering ES6: Unleashing the Power of the Latest JavaScript Features

In this blog, we are going to learn about ES6 features. We will try to cover most of the features that we use in our day-to-day coding some examples are arrow functions, rest operators, spread operators etc.

  1. Arrow functions: The arrow function provides a shorter syntax for defining the functions and making functions declaration code readable and more concise than normal function declaration. And they are called arrow functions because we use \=> operator to define the function. Let's see a simple example of an arrow function.

     // Normal funcion add to numbers
     function sum(a,b){
      return a + b;
     }
    
     // arrow function
     const sum => (a,b) => a+b; // because its single line then no retunrn also
    

    We can see how shorter and more concise arrow functions are and because of that function's code are more readable than our traditional functions.

    Also, they have a lexical binding of this keyword which means that the "this" keyword is automatically bound to the enclosing context.

    They do not have their own "arguments" object, which means that arguments must be passed as explicit parameters. This can make code more predictable. Let's understand this with one example.

     /*
       You see in traditional functions have this arguments which we 
       can use and because of that we don't need to pass parameters 
       but this can lead us to some confusion. And that' why with 
       arrow function you must have to pass arguments explicity.
     */
     // Normal function
     function sum() {
       let total = 0;
       // YES I HAVE THIS arguments
       for (let i = 0; i < arguments.length; i++) {
         total += arguments[i];
       }
       return total;
     }
     // Arrow functions does not have 
     const sum = (a,b,c) => {
       let total = a + b + c;
       return total;
     }
    
     console.log(sum(1, 2, 3)); // Output: 6
    
  2. Rest parameters: The rest parameter allows us to represent an indefinite number of arguments as an array. By using the rest parameter, a function can be called with any number of arguments. Given the example, you have some numbers and you want to return some of that numbers but what if you are not sure how many numbers we will have in that case rest parameters are useful.

    Let's understand by a simple example.

     // Normal way to some
     // I am best when you are sure you have exect same number of 
     // arguments
     const sum = (a,b,c) => {
       let total = a + b + c;
       return total;
     }
    
     // Bro i will handle for any number of argument you pass TRUST ME
     // This ... is basically rest operator simplest thing so no need 
     // to make it complicate
     // ... is array of arguments
     const sum = (...numbers) => {
       let total = 0;
       for(let i = 0 ; i < numbers.lengh ; i++){
          total+=numbers[i];
       }
      return total
     }
     console.log(sum(1, 11, 111)); // Output: hard to calculate :)
    

    Also, we can use rest parameter syntax with regular function parameters to represent a variable number of arguments. In that case, the rest parameter must be the last let's see an example of that also.

     function mySubjects(name, ...subjects) {
       console.log(`My name is , ${name}! and my selected subjects: `);
       for (let i = 0; i < subjects.length; i++) {
         console.log(subjects[i]);
       }
     }
    
     mySubjects("RAJU", "Maths", "Bio", "Physics");
    
     /* 
     Output :
     My name is , RAJU! and my selected subjects: 
     Maths
     Bio
     Physics
     */
    
  3. Destructuring: Destructuring is a way to extract values from objects or arrays and assign them to variables in a more concise way. Another definition of Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. That is, we can extract data from arrays and objects and assign them to variables. Let's understand it by example.

     /*
       Suppose you have list of student is sorted rank array now you
       show first , second and third rank together and then rest of
       student here in this case we use Destructuring.
     */
     let ranks = ["rohan","john","kita","haresh","khushi"];
     // lets use Destructuring
     const [first,second,third,...rest] = ranks;
    
     console.log(`Toppers are ${first} ${second} ${third}`);
     console.log(`Rest of students ${rest}`)
     /*
       Output 
       Toppers are rohan john kita
       Rest of students haresh,khushi
     */
    
     /*
      Same Destructuring we can do in object properies Lets see example
     */
    
     const person = {
       name: "Priyanshi",
       age: 23,
       gender: "Female",
       address: {
         city: "indore",
         state: "india"
       }
     };
     // see we can do nested level Destructuring also say thansk JS
     // Community
     const { name, age, address: { city } } = person;
    
     console.log(name); // Output: "Priyanshi"
     console.log(age); // Output: 23
     console.log(city); // Output: "indore"
    
  4. 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. Mostly we use it for combining different arrays into one copying the object and also we saw one example in destructuring [first, second, third,...rest] here this ...rest is also a spread operator and because of that we don't have to iterate through an array.

     // Combine all three arrays
     let one = [1,2,3];
     let two = [4,5,6];
     let three = [7,8,9];
     // see the magic how we are combining all three array with Spread   operator
     let combine = [...one,...two,...three];
     console.log(combine); // Output: [1, 2, 3, 4, 5, 6,7,8,9]
    

    Also, we can use the spread operator to pass an array as arguments in a function let's see an example.

     function greetings(x, y, z) {
       return x + y + z;
     }
     // i know it does not make much sense
     const greet = ["Hi"," How are you"," Doing"];
    
     console.log(greetings(...greet)) // Hi How are you Doing
    

    Also, we can use the Spread operator for copying objects and arrays and believe me or not you will use this many times in your day-to-day coding.

     const array = [1, 2, 3];
     const temp = [...array];
    
     console.log(temp); // Output: [1, 2, 3]
    
     const obj = { name: "Raju chacha", age: 18 };
     const tempObj = { ...obj };
    
     console.log(tempObj); // Output: { name: "Raju chacha", age: 18 };
    
  5. Template String: Template strings, also known as template literals, are a way to create strings that allow for embedding expressions and variables without the need for concatenation or escaping characters. They are enclosed by backticks ( ) instead of single or double quotes. Still, you will see many developer use + sign to concrete two or more strings but now we can use template strings to make our life easier and also make your code more readable for sure. Also for the multi-line string we don't need to use /n any more. Let's see one example.

    ```javascript const name = "Steve Jobs"; const age = 52;

    console.log(My name is ${name} and I am ${age} years old.); // Output: "My name is Steve Jobs and I am 52 years old."

    // Lets see one more example of multiline

const multiLineString = This is a multi-line string. and i don't know what to write.;

console.log(multiLineString); // Output: / This is a multi-line string. It spans across multiple lines. /


6. **Default function parameters**: This allows us to set default values for function parameters. This means that if a parameter is not provided when the function is called, it will take on the default value that you have specified. Let's see one example.

    ```javascript
    function greet(name = "who are you ?") {
      console.log(`Hello, ${name}!`);
    }
    greet(); // Output: "who are you!"
    greet("Obama"); // Output: "Hello, Obama!"

    // More good use case is in case of any mathmatical problem we 
    // should pass some default value
    function multiply(a, b=1) {
      return a * b;
    }

    // Try with without default value 1 you will get nan (Not an number) which is not really user friendly

    console.log(multiply(5)); // Output: 5 //
    console.log(multiply(5, 2)); // Output: 10
  1. Object shorthand notation: This one we will understand directly by example so suppose have two variables name and age with values "Steve jobs" and 52 now from this value you wanted to create an object user so how you will do it?

     // Old way to do 
     let name = "Steve jobs";
     let age = 52;
    
     let user = {
       name : name,
       age : age
      }
    

    As you can see we have some variables name and key that we are using in the object that is also the same like name: name and age: age in this kind of scenario when both are the same then we can simplify it as below.

     // New way to do thanks to object shorthand notation
     let name = "Steve jobs";
     let age = 52;
    
     let user = {name,age}; // Yep we can write like this for sure
    

    Now, apart from all these features we have a few more that we may cover in the next blog like classes, modules, promises, Symbols, and new methods in an array like map, filter and reduce.

    For a map, filtering and reducing we already have a blog that you can read and the same for promises these are details blogs about that specific topic.

That's all about ES6 Javascript fetures. And thanks to Akshay Saini for creating an incredible playlist this blog is just whatever learning I had from there. Also thanks for reading hope you have enjoyed it.