ES6
Restrict scope of a variable to blocks
(function(){ // open IIFE
var x = 3;
}()) // close IIFE
console.log(x); // ReferenceError
if(true){ // open block
let x = 3;
} // close block
console.log(x); // ReferenceError: x is not defined
In the above example x can not be accessed outside if block.
function a(x,y){
return ''+x+' and '+y+''; // concatenating using +
}
a(2,3);
function a(x,y){
return `${x} and ${y}` // template literals `${x}`
}
a(2,3);
Also template can span mulitple lines using literals
const a = `this is multiple line strings,
this can be achieved wit the help of teplate literals
`;
var arr = [1, 2, 3];
var squares = arr.map(function (x) { return x * x });
to
const arr = [1, 2, 3];
const squares = arr.map(x => x * x);
Handling multiple return values
var matchObj =
/^(\d\d\d\d)-(\d\d)-(\d\d)$/
.exec('2999-12-31');
var year = matchObj[1];
var month = matchObj[2];
var day = matchObj[3];
Handling multiple return values via destructuring
const [, year, month, day] =
/^(\d\d\d\d)-(\d\d)-(\d\d)$/
.exec('2999-12-31');
// pros: break and continue
// cons: initialisation var i = 0; Condtion i<arr.length; end point i++
var arr = ['a','b','c','d'];
for(var i =0; i<arr.length; i++){
console.log(arr[i]);
}
// pros: concise, less code, pass function as parameter
arr.forEach(el=>console.log(el));
Pass function as parameter to forEach
const num = [1,2,3,4,5,6];
let sum = 0;
function addNumber(number){
sum+=number;
}
num.forEach(addNumber); // Passing addNumber function as parameter to forEach
console.log(sum); //21
// for-of combines both advantages
var arr = ['a','b','c','d'];
for(const ele of arr){
console.log(ele);
}
Get both index and values using array.entries() and destructuring
// to get both index and values using array.entries() and destructuring
for(const[index, ele] of arr.entries()){
console.log(index, ele);
}