Java, .NET, PHP, PYTHON, ANGULAR, ML, Data Science, Testing, CI Tutorials in Easy Languages.

"Best Software Training, Internship, Project Development center of Indore India, Helpline 780506-3968"

                                        


JavaScript ES6 Concept:-

It is used to provide additional features to JavaScript objects.

JavaScript was created by Brendan Eich in 1995 and became an ECMA standard in 1997.

ECMAScript is the official name of the language.

ECMAScript versions have been abbreviated to ES1, ES2, ES3, ES5, and ES6.

1) let, const, and var

The let keyword allows you to declare a variable with block scope.

Example

var a = 10;

// Here a is 10

{

  let a = 2;

  // Here a is 2

}

// Here a is 10

The const keyword allows you to declare a constant (a JavaScript variable with a constant value).

Constants are similar to let variables, except that the value cannot be changed.

var x = 10;

// Here x is 10

{

  const x = 2;

  // Here x is 2

}

// Here x is 10


Call back function in JavaScript:-

A callback is a function passed as an argument to another function.

Using a callback, you could call the calculator function (myCalculator) with a callback, and let the calculator function run the callback after the calculation is finished.

When to Use a Callback?

Where callbacks really shine is in asynchronous functions, where one function has to wait for another function (like waiting for a file to load).

function myDisplayer(some) {

  document.getElementById("demo").innerHTML = some;

}

function myCalculator(num1, num2, myCallback) {

  let sum = num1 + num2;

  myCallback(sum);

}

myCalculator(5, 5, myDisplayer);


Arrow Functions

Arrow functions allow a short syntax for writing function expressions.

You don't need the function keyword, the return keyword, and the curly brackets.

Syntax:-

const identifier = ()=>expression



// ES5

var x = function(x, y) {

   return x * y;

}


// ES6

const x = (x, y) => x * y;


The For/Of Loop

The JavaScript for/of statement loops through the values of an iterable objects.


for/of lets you loop over data structures that are iterable such as Arrays, Strings, Maps, NodeLists, and more.


The for/of loop has the following syntax:


for (variable of iterable) {

  // code block to be executed

}


const cars = ["BMW", "Volvo", "Mini"];

let text = "";

for (let x of cars) {

  text += x + " ";

}


let language = "JavaScript";

let text = "";


for (let x of language) {

    text += x + " ";

}

JavaScript Maps:-

identifer = new Map()

identifer.set(key:value)


const apples = {name: 'Apples'};

const bananas = {name: 'Bananas'};

const oranges = {name: 'Oranges'};


// Create a new Map

const fruits = new Map();


// Add new Elements to the Map

fruits.set(apples, 500);

fruits.set(bananas, 300);

fruits.set(oranges, 200);


JavaScript Sets:-

Example

// Create a Set

const letters = new Set();


// Add some values to the Set

letters.add("a");

letters.add("b");

letters.add("c");


JavaScript Classes:-

JavaScript Classes are templates for JavaScript Objects. it is used to define the characteristics and behavior of the object. Use the keyword class to create a class.


Always add a method named constructor():


class ClassName {

  constructor() { ... }

}


class Car {

  constructor(name, year) {

    this.name = name;

    this.year = year;

  }

}


const myCar1 = new Car("Ford", 2014);

const myCar2 = new Car("Audi", 2019);


JavaScript Promises:-

A Promise is a JavaScript object that links "Producing Code" and "Consuming Code".


"Producing Code" can take some time and "Consuming Code" must wait for the result.

JavaScript is single-threaded, meaning that two bits of the script cannot run at the same time; they have to run one after another. A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

const myPromise = new Promise(function(my resolve, myReject) {

// "Producing Code" (May take some time)


  myResolve(); // when successful

  myReject();  // when error

});


// "Consuming Code" (Must wait for a fulfilled Promise).

myPromise.then(

  function(value) { /* code if successful */ },

  function(error) { /* code if some error */ }

);


Example Using a Promise

const myPromise = new Promise(function(myResolve, myReject) {

  setTimeout(function() { myResolve("Wecome in SCS !!"); }, 3000);

});


myPromise.then(function(value) {

  document.getElementById("demo").innerHTML = value;

});


Another Example:-

Promises can be chained together

When writing Promises to solve a particular problem, you can chain them together to form logic.


var add = function(x, y) {

  return new Promise((resolve,reject) => {

    var sum = x + y;

    if (sum) {

      resolve(sum);

    }

    else {

      reject(Error("Could not add the two values!"));

    }

  });

};


var subtract = function(x, y) {

  return new Promise((resolve, reject) => {

    var sum = x - y;

    if (sum) {

      resolve(sum);

    }

    else {

      reject(Error("Could not subtract the two values!"));

    }

  });

};


// Starting promise chain

add(2,2)

  .then((added) => {

    // added = 4

    return subtract(added, 3);

  })

  .then((subtracted) => {

    // subtracted = 1

    return add(subtracted, 5);

  })

  .then((added) => {

    // added = 6

    return added * 2;    

  })

  .then((result) => {

    // result = 12

    console.log("My result is ", result);

  })

  .catch((err) => {

    // If any part of the chain is rejected, print the error message.

    console.log(err);

  });

 The Symbol Type:-

A JavaScript Symbol is a primitive datatype just like a Number, String, or Boolean.

It represents a unique "hidden" identifier that no other code can accidentally access.

For instance, if different coders want to add a person.id property to a person's object belonging to a third-party code, they could mix each other's values.


Using Symbol() to create a unique identifiers, solves this problem:

<!DOCTYPE html>

<html>

<body>


<h2>Using JavaScript Symbol()</h2>


<p id="demo"></p>


<script>

const person = {

  firstName: "John",

  lastName: "Doe",

  age: 50,

  eyeColor: "blue"

};


let id = Symbol('id');

person[id] = 140353;


document.getElementById("demo").innerHTML = person[id] + " " + person.id;

</script>


</body>

</html>


Default Parameter Values:-

ES6 allows function parameters to have default values.


Example

function myFunction(x, y = 10) {

  // y is 10 if not passed or undefined

  return x + y;

}

myFunction(5); // will return 15


Function Rest Parameter:-

The rest parameter (...) allows a function to treat an indefinite number of arguments as an array:


function sum(...args) {

  let sum = 0;

  for (let arg of args) sum += arg;

  return sum;

}


let x = sum(4, 9, 16, 25, 29, 100, 66, 77);


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!`


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}`   


Modules in JavaScript:-


  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


Create File Name FirstModule.js and Write this code

export var name = "XYZ"
export default function getName()
{
    console.log("welcome")
}

Create Second File Name SecondModule.html
 <script type="module">
        import getName from "./FirstModule.js";
            getName();
    </script>



Post a Comment

POST Answer of Questions and ASK to Doubt

Previous Post Next Post