var vs let vs const
var
: function block. If declared globally, scope is global.
let
: block level
const
: block level
/*Using var to declare variables*/
function usingVar(){
for(var i=0;i<2;i++){ // var declaration
console.log('In loop: '+ i);
}
console.log('After loop : '+ i);
}
usingVar();
Output:
In loop: 0
In loop: 1
After loop: 2
/*Using let to declare variables*/
function usingLet(){
for(let i=0;i<2;i++){ // let declaration
console.log('In loop: '+ i);
}
console.log('After loop : '+ i);
}
usingLet();
Output:
In loop: 0
In loop: 1
Uncaught ReferenceError: i is not defined
/* i is not available outside 'for' block because it is declared using let keyword*/
Class
Arrow functions
/*If more than one parameters*/
name = (one, two) => {
return one + two;
}
/*If only receive one parameter*/
name = parameter => {
return parameter;
}
/*If no parameter*/
name = () => {
console.log('Hello World')
}
/*If there is only a return statement, we can exclude {} and return*/
name = (one,two) => one + two;
this in array functions
/*With simple callback function*/
var self = this;
$('.btn').click(function(event){
self.anyMethod()
})
/*With arrow functions as callback function*/
$('.btn').click((event)=>{
this.anyMethod()
})
Template Literals
let name='Gurinder';
let age= 25;
let info= "My name is "+ name +" and age is "+ age +" years";
/*Using template literals*/
let name='Gurinder';
let age= 25;
let info= `My name is ${name} and age is ${age} years`
Object Destructuring
name : 'Gurinder',
age : 25,
website: 'gurindershergill.in'
}
/*If we need to extract info of person object to variables
Without Object Destructuring*/
var name = person.name;
var age= person.age;
var website = person.website;
/*Using Object Destructuring*/
var {name, age, website} = person; // this will create 3 variables and extract information from person object and will assign to variables.
var {name:nm, website:web} = person // if we want to use another name for variables other than object keys,we can use ":" to give alias name.
Spread Operator
/*Object Cloning using spread operator*/
var person = {
name : 'Gurinder',
age : 25,
website: 'gurindershergill.in'
}
var anotherPerson = {...person} //Object clone, as simple as that
/*Array Cloning using spread operator*/
var numbers = [1,2,3,4,5,6,7,8]
var anotherNumbers = [...numbers] // Array cloned
/*Combining Objects*/
/*We can easily combine multiples object and can also add more properties using spread operator*/
var person = {
name : 'Gurinder',
age : 25,
website: 'gurindershergill.in'
}
var university = {
uniName: 'Thapar University',
location : 'Patiala'
}
var fullInfo = {...person,...university, company:'Nagarro'};
//This will create a new object by combining.
/*Combining Arrays*/
/*We can easily combine multiples arrays and can also add more items using spread operator*/
var numbers = [1,2,3];
var moreNumbers = [5,6,7,8];
var allNumbers = [...numbers,4,...moreNumbers];
//This will create a new array by combining.