ES5 to ES6
function to =>
Let's start with the basic ES5 function.function sayHello(name){ console.log("Hello" + name); }
Let us assign the above function to a variable sayHello,
var sayHello = function (name){ console.log("Hello "+name); }
Let's transform es5 function to es6 function,
Step 1 : Get rid of function
var sayHello = (name){
Step 2 : introduce a new symbol => which is going to replace the word function
var sayHello = =>(name)
Step 3 : Move the => after the ()
var sayHello = (name) =>
That's it, now look at the transformation of the es5 to es6
var sayHello = (name) => { console.log("Hello "+name); }
That was beginner level stuff, let's make it shorter like a pro, by getting rid of parentheses around "name", so to add your knowledge level, you don't need enclose your argument with (), if there is only one argument, you need (), only if there are no argument or more than one argument.
var sayHello = name => { console.log("Hello " + name); }
Let us make it more es6, by replacing var with const
const sayHello = name => { console.log("Hello " + name); }
We can further shorten it to single line, like as follows, since our function is having only one line then we don't need to enclose the function to braces, I know it sometimes doesn't look neat or readable but just an option, and don't get overwhelmed and get confused if some one else did.
const sayHello = name => console.log("Hello " + name);
Now the last step is using the new back tick, which can be found at the top left corner and mostly below esc key, which may look like this `.
So we no longer need to manage + "" + "" and make sure everything is properly started and end.
const sayHello = name => console.log(`Hello ${name}`);
I am still wondering why we call it as arrow function because arrow is coming after this () , shouldn't we call as function arrow () = function => arrow ()=> function arrow, yeah I know it sounds weird :).
for to forEach
ES5 Code with for loop
(()=>{ const nbrArray = [1,2,3,4,5,6,7,8,9,10] //ES5 for loop for(var i=0 ; i < nbrArray.length ; i++){ console.log(i +"=>"+nbrArray[i]); } })()
ES6 Code with forEach
(()=>{ const nbrArray = [1,2,3,4,5,6,7,8,9,10] //ES6 forEach nbrArray.forEach((nbr, i)=>{ console.log(`${i} => ${nbr}`); }) })()
for to map
ES5 Code with for loop
(()=>{ const nbrArray = [1,2,3,4,5,6,7,8,9,10]; let nbrArrayMultipliedWithTwo = []; //ES5 for loop, to convert original array value, multiplies with 2 for(var i=0 ; i < nbrArray.length ; i++){ nbrArrayMultipliedWithTwo[i] = nbrArray[i] * 2 } console.log(nbrArrayMultipliedWithTwo); })()
ES6 Code with map
(()=>{ const nbrArray = [1,2,3,4,5,6,7,8,9,10]; let nbrArrayMultipliedWithTwo = []; //ES6 -> map, converting and returning the converted array to new array nbrArrayMultipliedWithTwo = nbrArray.map((nbr, i)=>{ return nbr * 2; }) console.log(nbrArrayMultipliedWithTwo); })()
for to reduce
ES5 code with for loop
(()=>{ const nbrArray = [1,2,3,4,5,6,7,8,9,10]; let sum = 0; //ES5 for loop, to convert original array value, multiplies with 2 for(var i=0 ; i < nbrArray.length ; i++){ sum += nbrArray[i]; } console.log(sum); })()
ES6 with reduce()
(()=>{ const nbrArray = [1,2,3,4,5,6,7,8,9,10]; let sum = 0; //ES6 -> reduce, sum of all then number inside the array, inProgress data
//contains the sum of the number till each iteration. sum = nbrArray.reduce((inProgressData, nbr)=>{ return inProgressData + nbr; }, 0) console.log(sum); })()
Another example to concatenate array element using reduce.
(()=>{ const nameArray = ["vikash","vijay","Vimal","Vidyut","No Idea"]; //ES6 -> map, converting and returning the converted array to new array let joinedName = nameArray.reduce((inProgressData, nbr)=>{ return inProgressData ? inProgressData +','+ nbr : inProgressData + nbr; }, "") console.log(joinedName); })()Output : vikash,vijay,Vimal,Vidyut,No Idea
for to filter :
Many times we want to filter the data based on the certain condition and also store the filtered data into another variable. We can use the filter to do the similar stuff, before that let's take a look what we usually do in ES5ES5 Code with for loop
(()=>{ const nameArray = ["vikash","vijay","Vimal","Vidyut","No Idea"]; const pattern = /^v/i; const filteredArray = []; for(var i=0 ; i < nameArray.length ; i++){ if(pattern.test(nameArray[i])){ filteredArray.push(nameArray[i]); } } console.log(filteredArray);})();[ 'vikash', 'vijay', 'Vimal', 'Vidyut' ]
Now we can do the same using the filter(), the filter() will iterate through each element of array, and also call the callback function, the callback function should return true or false, if callback function returns true then element will be kept on resultant array else will be discarded.
ES6 Code with Filter
(()=>{ const nameArray = ["vikash","vijay","Vimal","Vidyut","No Idea"]; const pattern = /^v/i; const filteredArray = nameArray.filter((name)=>{ return pattern.test(name); }); console.log(filteredArray);})();
Map()
It's not like we can't simulate the Map using the object, either in es6 or es5 but just a convenience may be but let's see how can we have map simulation using object.ES5 code with JSON
(() => { const es5SocialAccount = {} es5SocialAccount.google = true; es5SocialAccount.yahoo = false; es5SocialAccount.facebook = true; es5SocialAccount.linkedIn = false; Object.keys(es5SocialAccount).forEach((key) => console.log(key, es5SocialAccount[key])) if (es5SocialAccount.google) { console.log("I have google account"); } else { console.log("I don't have google account"); } if (es5SocialAccount.hasOwnProperty("yahoo")) { console.log("I may have yahoo account or may be I am planning to create one"); } else { console.log("there is no plan to create a yahoo account"); } })();
But in ES6 we can use Map() to do the similar activity, using more convenient setter and getter method let us take a look at the below example.
Es6 Code with Map()
(() => { const es6SocialAccount = new Map(); //Easier setting of data es6SocialAccount.set("google", true); es6SocialAccount.set("yahoo", false); es6SocialAccount.set("facebook", true); es6SocialAccount.set("linkedIn", false); //Easier iteration es6SocialAccount.forEach((value, key) => console.log(key, value)) if (es6SocialAccount.get("google")) { console.log("I have google account"); } else { console.log("I don't have google account"); } if (es6SocialAccount.has("yahoo")) { console.log("I may have yahoo account or may be I am planning to create one"); } else { console.log("there is no plan to create a yahoo account"); } })();
Special : Using Iterator of Map() :
(() => { const es5SocialAccount = new Map(); es5SocialAccount.set("google", true); es5SocialAccount.set("yahoo", false); es5SocialAccount.set("facebook", true); es5SocialAccount.set("linkedIn", false); let keyIterator = es5SocialAccount.keys(); let key; while (!(key = keyIterator.next()).done) { console.log(key.value) } let valueIterator = es5SocialAccount.values(); let value; while (!(value = valueIterator.next()).done) { console.log(value.value) } })();
map -> filter -> reduce chaining example
(()=>{ let nbrArray = [1,2,3,4,5,6,7,8,9,10] let sumOfEvenNumber = nbrArray.map((nbr)=>{ return nbr*3 //Multiplying every number with 3 and returning the converted array }).filter((nbr) => { return (nbr % 2 === 0) //returning only even number }).reduce((inpProgressValue, nbr)=> { return inpProgressValue + nbr; //summing all the even number and returing the final sum }, 0) console.log(sumOfEvenNumber);})()
We can shorten this further and make it look compact.
(() => { let nbrArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] let sumOfEvenNumber = nbrArray .map(nbr => nbr * 3) //Multiplying every number with 3 and returning the converted array .filter(nbr => nbr % 2 === 0) //returning only even number .reduce((inpProgressValue, nbr) => inpProgressValue + nbr, 0) //summing all the even number and returing the final sum console.log(sumOfEvenNumber); })()
Comments
Post a Comment