Ecma 6: Diff Between Let and Var
Ecma 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.
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
CODE # 1:
<html>
<body>
<script>
var x = 5;
document.write(x, "\n");
let y = 10;
document.write(y, "\n");
document.write(z, "\n");
var z = 2;
document.write(a);
let a = 3;
</script>
</body>
</html>
Code # 2:
<!DOCTYPE html>
<html>
<head>
<title>Var vs Let</title>
</head>
<body>
<script type="text/javascript">
function colour() {
setInterval(function() {
if (document.getElementById('var').style.color == 'black')
else
col1 = 'black';
if (document.getElementById('let').style.color == 'black') {
} else {
col2 = 'black';
document.getElementById('var').style.color = col1;
document.getElementById('let').style.color = col2;
}, 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:
<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:
<p id="demo"></p>
<script>
return x + y;
document.getElementById("demo").innerHTML = myFunction(5);
</script>
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:
Before:
hello = function() {
return "Hello World!";
}
After:
hello = () => {
return "Hello World!";
}
Ex:
<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>
</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
<p id="demo"></p>
<script>
</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);
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.
Ex:
var Student = class{
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.
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.
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:
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.
The keyword “await” makes JavaScript wait until that promise settles and returns its result.
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.
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 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.