0% found this document useful (0 votes)
9K views15 pages

Ecma 6: Diff Between Let and Var

ECMAScript is a standard for scripting languages like JavaScript. ECMAScript 2015 (ES6) introduced many new features to JavaScript including let and const block scope variables, default function parameters, arrow functions, enhanced object literals, classes, modules and more. Callbacks allow functions to be passed as parameters and executed after another function has completed.

Uploaded by

mamidi sudeep
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
9K views15 pages

Ecma 6: Diff Between Let and Var

ECMAScript is a standard for scripting languages like JavaScript. ECMAScript 2015 (ES6) introduced many new features to JavaScript including let and const block scope variables, default function parameters, arrow functions, enhanced object literals, classes, modules and more. Callbacks allow functions to be passed as parameters and executed after another function has completed.

Uploaded by

mamidi sudeep
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 15

ECMA 6

European Computer Manufacturers Association (ECMAScript) or (ES) is a standard for scripting


languages like JavaScript, ActionScript and JScript. It was initially created to standardize JavaScript,
which is the most popular implementation of ECMAScript.

ECMAScript 2015 was the second major revision to JavaScript.

ECMAScript 2015 is also known as ES6 and ECMAScript 6.

Diff between let and var:

var and let are both used for variable declaration in javascript but the difference between them is that
var is function scoped and let is block scoped.
It can be said that a variable declared with var is defined throughout the program as compared to let.

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

Ex of var:

console.log(x);
var x=5;
console.log(x);

Output:
undefined
5

Ex of let:

console.log(x);
let x=5;
console.log(x);

Output:
Error

Ex: var x = 10;


// Here x is 10
{
  let x = 2;
  // Here x is 2
}
// Here x is 10

CODE # 1:

<html>
<body>

<script>

// calling x after definition

var x = 5;

document.write(x, "\n");

// calling y after definition

let y = 10;

document.write(y, "\n");

// calling var z before definition will return undefined

document.write(z, "\n");

var z = 2;

// calling let a before definition will give error

document.write(a);

let a = 3;

</script>

</body>

</html>

Code # 2:

<!DOCTYPE html>

<html>

<head>

<title>Var vs Let</title>

</head>

<body>

<h1 id="var" style="color:black;">Try me with VAR</h1>

<h1 id="let" style="color:black;"> Try me with LET </h1>

<button id="btn" onclick="colour()">Start</button>

<!-- executing function on button click -->

<script type="text/javascript">
function colour() {

setInterval(function() {

if (document.getElementById('var').style.color == 'black')

var col1 = 'blue';

else

col1 = 'black';

// setting value of color 1 through var

if (document.getElementById('let').style.color == 'black') {

let col2 = 'red';

} else {

col2 = 'black';

// setting value of color 2 through let

document.getElementById('var').style.color = col1;

document.getElementById('let').style.color = col2;

// changing color of h1 in html

}, 500);

</script>

</body>

</html>

Const keyword:

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.

Ex:

<h2>Declaring a Variable Using const</h2>

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

<script>
var x = 10;

// Here x is 10

const x = 2;

// Here x is 2

// Here x is 10

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

</script>

Functions:

ES6 allows function parameters to have default values.

Ex: <h2>Default Parameter Values</h2>

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

<script>

function myFunction(x, y = 10) {

// y is 10 if not passed or undefined

return x + y;

document.getElementById("demo").innerHTML = myFunction(5);

</script>

Ex: function say(message='Hi') {

console.log(message);

say(); // 'Hi'

say('Hello') // 'Hello'

In JavaScript, default function parameters allow you to initialize named parameters with default values if
no values or undefined are passed into the function.

In the above example, the default value of the message parameter in the say() function is 'Hi'
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.

Before:

hello = function() {
  return "Hello World!";
}

After:

hello = () => {
  return "Hello World!";
}

Ex:

<h2>JavaScript Arrow Functions</h2>

<p>With arrow functions, you don't have to type the function keyword, the return keyword, and the
curly brackets.</p>

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

<script>

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

document.getElementById("demo").innerHTML = x(5, 5);

</script>

Using const is safer than using var, because a function expression is always a constant value.

You can only omit the return keyword and the curly brackets if the function is a single statement.
Because of this, it might be a good habit to always keep them

Ex: <h2>JavaScript Arrow Functions</h2>

<p>Arrow functions are not supported in IE11 or earlier.</p>

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

const x = (x, y) => { return x * y };

document.getElementById("demo").innerHTML = x(5, 5);

</script>

Objects:

Objects are the collection of key/value pairs that can be modified throughout the lifecycle of an object
as similar to hash map or dictionary. Objects allow us to define custom data types in JavaScript.

An object can be created by using curly braces {...} along with an optional properties list. The property is
a "key:value" pair, where the key is a string or a property name, and the value can be anything.

Syntax:

1. var user =  {};  // 'object literal' syntax  
2. var name = new Object();  //'object constructor' syntax  

In ES5,

function user(name, division) {  
    return {  
        name: name,  
        divison: division  
    };  
}

The above function user() takes two arguments, which are name and division, and returns a new object
literal having two properties name and division. The property name and division take the values of the
function parameters.

The above syntax looks repetitive because the name and division mentioned twice in keys and values of
properties.

The syntax in ES6 eliminates the duplication when an object property is the same as the name of a local
variable.

In ES6,
function user(name, division) {  
    return {  
        name,  
        divison  
    };  
}
Ex:
let uname = 'Anil',  
    udivision = 'First';  
   
let user = {  
   uname,  
   udivision  
};  
console.log(user.uname);  
console.log(user.udivision); 

Computed Property Name:

Before ES6, we could use the square brackets [] to enable the computed property names for the object
properties. Square bracket notation allows us to use variables and string literals as the name of the
property.

ES6 introduced a new feature 'computed property names,' which is a part of object literal syntax, and it
uses the square bracket [] notation. It allows us to put an expression within the square brackets [] that
will be computed and used as the name of the property.

In ES5,
var emp = {  
    id : 101,  
    name : 'Amit'  
}  
var department = 'dep_name';  
emp[department]='Sales';  
console.log(emp); 

In ES6,
var department = 'dep_name';  
var emp = {  
    id : 102,  
    name : 'Anil',  
    [department]:'Production'  
}  
console.log(emp);

ES6 Classes:

Before ES6, it was hard to create a class in JavaScript. But in ES6, we can create the class by using
the class keyword. We can include classes in our code either by class expression or by using a class
declaration.
A class definition can only include constructors and functions. These components are together called as
the data members of a class. The classes contain constructors that allocates the memory to the objects
of a class. Classes contain functions that are responsible for performing the actions to the objects.

Syntax of class expression:


var var_name = new class_name {  
}

Ex:
var Student = class{  
    constructor(name, age){  
    this.name = name;  
    this.age = age;  
    }  

Syntax of class declaration:


class Class_name{  
}  
Ex:
class Student{  
    constructor(name, age){  
    this.name = name;  
    this.age = age;  
    }  
}  

Like other object-oriented programming languages, we can instantiate an object from class by using the
new keyword.

Ex: var stu = new Student('Peter', 22)

Accessing functions:

The object can access the attributes and functions of a class. We use the '.' dot notation (or period) for
accessing the data members of the class.

Ex:
class Student {   
   constructor(name, age) {   
      this.n = name;   
      this.a = age;  
   }   
   stu() {   
      console.log("The Name of the student is: ", this.n)   
      console.log("The Age of the student is: ",this. a)   
   }   
}   
  
var stuObj = new Student('Peter',20);   
stuObj.stu();

Callback functions:

A Callback is a way to handle the function execution after the completion of the execution of another
function.
A Callback would be helpful in working with events. In Callback, a function can be passed as a parameter
to another function.

Ex:
function print(callback) {
callback();
}

The print( ) function takes another function as a parameter and calls it inside. This is valid in JavaScript
and we call it a “callback”. So a function that is passed to another function as a parameter is a callback
function.
JavaScript runs code sequentially in top-down order. However, there are some cases that code runs (or
must run) after something else happens and also not sequentially. This is called asynchronous
programming.

Callbacks make sure that a function is not going to run before a task is completed but will run right after
the task has completed. It helps us develop asynchronous JavaScript code and keeps us safe from
problems and errors.

In JavaScript, the way to create a callback function is to pass it as a parameter to another function, and
then to call it back right after something has happened or some task is completed.

Ex:
const message = function() {
console.log("This message is shown after 3 seconds");
}

setTimeout(message, 3000);

A Callback is a great way when dealing with basic cases like minimal asynchronous operations. But when
you are developing a web application that has a lot of code, then working with Callback will be messy.
This excessive Callback nesting is often referred to as Callback hell.

To deal with such cases, we have to use Promises instead of Callbacks.


Promises:

A Promise represents something that is eventually fulfilled. A Promise can either be rejected or resolved
based on the operation outcome.

ES6 Promise is the easiest way to work with asynchronous programming. Asynchronous programming
includes the running of processes individually from the main thread and notifies the main thread when it
gets complete.

Pending - It is the initial state of each Promise. It represents that the result has not been computed yet.

Fulfilled - It means that the operation has completed.

Rejected - It represents a failure that occurs during computation.

Once a Promise is fulfilled or rejected, it will be immutable. The Promise() constructor takes two


arguments that are rejected function and a resolve function. Based on the asynchronous operation, it
returns either the first argument or second argument.

Syntax: const Promise = new Promise((resolve,reject) => {....});  

Ex:

let Promise = new Promise((resolve, reject)=>{  
    let a = 3;  
    if(a==3){  
        resolve('Success');  
    }  
    else{  
        reject('Failed');  
    }  
})  
Promise.then((message)=>{  
    console.log("It is then block. The message is:  “?+ message)  
}).catch((message)=>{  
console.log("It is Catch block. The message is:  “?+ message)  
})
It is then block. The message is: Success

Output:
It is then block. The message is: Success

Methods:

The Promise methods are used to handle the rejection or resolution of the Promise object.

.then()

It takes two functional arguments for resolved and rejected. The first one gets invoked when the
Promise is fulfilled, and the second one (which is optional) gets invoked when the Promise is rejected.

Ex:

let success = (a) => {  

    console.log(a + " it worked!")  

  }

  let error = (a) => {  

    console.log(a + " it failed!")  

  }      

  const Promise = num => {  

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

      if((num%2)==0){  

        resolve("Success!")  

      }  
      reject("Failure!")  

    })  

  }      

  Promise(100).then(success, error)   

  Promise(21).then(success,error) 

Output:

Success! it worked!

Failure! it failed!

.catch()

It is a great way to handle failures and rejections. It takes only one functional argument for handling the
errors.

Async/ Await:

There’s a special syntax to work with promises in a more comfortable fashion, called “async/await”.

Ex:

async function f() {


return 1;

The word “async” before a function means one simple thing: a function always returns a promise. Other
values are wrapped in a resolved promise automatically.

async function f() {


return Promise.resolve(1);
}
f().then(alert);

The keyword “await” makes JavaScript wait until that promise settles and returns its result.

async function f() {

let promise = new Promise((resolve, reject) => {


setTimeout(() => resolve("done!"), 1000)
});
let result = await promise; // wait until the promise resolves (*)

alert(result); // "done!"
}

f();

 await literally
suspends the function execution until the promise settles, and then resumes it with the
promise result. That doesn’t cost any CPU resources, because the JavaScript engine can do other jobs in
the meantime: execute other scripts, handle events, etc.

Note: We cannot use await in regular functions

Modules:

Modules are the piece or chunk of a JavaScript code written in a file. JavaScript modules help us to
modularize the code simply by partitioning the entire code into modules that can be imported from
anywhere. Modules make it easy to maintain the code, debug the code, and reuse the piece of code.
Each module is a piece of code that gets executed once it is loaded.

Exporting and Importing a Module

Exporting a Module:

JavaScript allows us to export a function, objects, classes, and primitive values by using
the export keyword. There are two kinds of exports:

o Named Exports: The exports that are distinguished with their names are called as named
exports. We can export multiple variables and functions by using the named export.
o Default Exports: There can be, at most, one value that can be exported by using the default
export.

Importing a Module:

The values which are exported from the module can be imported by using the  import keyword. We can
import the exported variables, functions, and classes in another module. To import a module, we simply
have to specify their path.

Ex of export module:

//Named export in class  
class Nokia{  
//properties  
//methods  
}  
export {Nokia}; //Named export  
  
//Named export in functions  
function show(){  
}  
export {show};  
  
//Named export in Variables  
const a = 10;  
export {a};  

Ex:

Mobile.js-

class Nokia{  
//properties  
//methods  
}  
function show(){  
}  
const a = 10;
export {Nokia, show};  

Ex of import module:

App.js-

import {Nokia, show} from './Mobile.js';

Importing all-

import * as device from './Mobile.js';

Array Destructuring:

Destructuring means to break down a complex structure into simpler parts. With the syntax of
destructuring, you can extract smaller fragments from objects and arrays. It can be used for assignments
and declaration of a variable.

Destructuring is an efficient way to extract multiple values from data that is stored in arrays or objects.
When destructuring an array, we use their positions (or index) in an assignment.

Ex:

var arr = ["Hello", "World"]  
  
// destructuring assignment  
var [first, second] = arr;  
  
console.log(first); // Hello  
console.log(second); // World

The left-hand side of destructuring assignment is for defining what values are required to unpack from
sourced variable.

You might also like