-
Destructuring, Spread, Rest parameters, Default parameters, Maps and ArraysDynamicPL/Javascript 2019. 10. 24. 19:28
1. Overview
There are several new features added in ES6 which are Destructing, Spread, Rest, Default parameter, and so on.
2. Description
2.1 Destructing
// ES5 var john = ['John', 26]; //var name = john[0]; //var age = john[1]; // ES6 // assign each element to variable const [name, age] = ['John', 26]; console.log(name); console.log(age); const obj = { firstName: 'John', lastName: 'Smith' }; const {firstName, lastName} = obj; console.log(firstName); console.log(lastName); // switching variable name const {firstName: a, lastName: b} = obj; console.log(a); console.log(b); function calcAgeRetirement(year) { const age = new Date().getFullYear() - year; return [age, 65 - age]; } const [age2, retirement] = calcAgeRetirement(1990); console.log(age2); console.log(retirement);
2.2 Arrays in ES6
// querySelectorAll methods does not return an array, but a node list. const boxes = document.querySelectorAll('.box'); //ES5 // transform a node list into an array. var boxesArr5 = Array.prototype.slice.call(boxes); boxesArr5.forEach(function(cur) { cur.style.backgroundColor = 'dodgerblue'; }); //ES6 // Problem of forEach is we cannot "break" from them and also not use the "continue" // Map also has same problem. const boxesArr6 = Array.from(boxes); Array.from(boxes).forEach(cur => cur.style.backgroundColor = 'dodgerblue'); //ES5 for(var i = 0; i < boxesArr5.length; i++) { if(boxesArr5[i].className === 'box blue') { continue; } boxesArr5[i].textContent = 'I changed to blue!'; } //ES6 for (const cur of boxesArr6) { if (cur.className.includes('blue')) { continue; } cur.textContent = 'I changed to blue!'; } //ES5 var ages = [12, 17, 8, 21, 14, 11]; var full = ages.map(function(cur) { return cur >= 18; }); console.log(full); console.log(full.indexOf(true)); console.log(ages[full.indexOf(true)]); //ES6 // Doing more concise way console.log(ages.findIndex(cur => cur >= 18)); console.log(ages.find(cur => cur >= 18));
2.3 Spread Operator
The Spread operator takes an array in basically and transforms it into single values.
function addFourAges (a, b, c, d) { return a + b + c + d; } var sum1 = addFourAges(18, 30, 12, 21); console.log(sum1); //ES5 var ages = [18, 30, 12, 21]; // apply method receive an array as second parameter. And here, we aren't interested in this, set it null. // Then call addFourAges using elements of the array as the arguments var sum2 = addFourAges.apply(null, ages); console.log(sum2); //ES6 // expands array into its components const sum3 = addFourAges(...ages); console.log(sum3); const familySmith = ['John', 'Jane', 'Mark']; const familyMiller = ['Mary', 'Bob', 'Ann']; const bigFamily = [...familySmith, 'Lily', ...familyMiller]; console.log(bigFamily); // we can actually use spread operator on another structures so not just array but // , for example, also on a node list. const h = document.querySelector('h1'); const boxes = document.querySelectorAll('.box'); const all = [h, ...boxes]; Array.from(all).forEach(cur => cur.style.color = 'purple');
2.4 Rest parameters
Rest parameters allow us to pass an arbitrary number of arguments into a function. The notation is exactly the same as the Spread operator but works totally different. Rest parameter receives a couple of single values and transforms them into an array when we call a function with multiple parameters. Rest operator is used in the function declaration.
//ES5 function isFullAge5() { //console.log(arguments); // In ES5, if wanting receive undefined number of arguments, then we simply don't define // any parameters for our function and then just use the arguments keyword. // And it isn't array but array-like structured object. // So if you want to loop through it, transform it into array. var argsArr = Array.prototype.slice.call(arguments); argsArr.forEach(function(cur) { console.log((2016 - cur) >= 18); }) } //isFullAge5(1990, 1999, 1965); //isFullAge5(1990, 1999, 1965, 2016, 1987); //ES6 function isFullAge6(...years) { years.forEach(cur => console.log( (2016 - cur) >= 18)); } isFullAge6(1990, 1999, 1965, 2016, 1987); //ES5 function isFullAge5(limit) { // slice method allows us to cut a piece of an array just like below which start cutting // and copying at position 1 var argsArr = Array.prototype.slice.call(arguments, 1); argsArr.forEach(function(cur) { console.log((2016 - cur) >= limit); }) } //isFullAge5(16, 1990, 1999, 1965); isFullAge5(1990, 1999, 1965, 2016, 1987); //ES6 function isFullAge6(limit, ...years) { years.forEach(cur => console.log( (2016 - cur) >= limit)); } isFullAge6(16, 1990, 1999, 1965, 2016, 1987);
2.5 Default parameters
// ES5 function SmithPerson(firstName, yearOfBirth, lastName, nationality) { lastName === undefined ? lastName = 'Smith' : lastName = lastName; nationality === undefined ? nationality = 'american' : nationality = nationality; this.firstName = firstName; this.lastName = lastName; this.yearOfBirth = yearOfBirth; this.nationality = nationality; } //ES6 function SmithPerson(firstName, yearOfBirth, lastName = 'Smith', nationality = 'american') { this.firstName = firstName; this.lastName = lastName; this.yearOfBirth = yearOfBirth; this.nationality = nationality; } var john = new SmithPerson('John', 1990); var emily = new SmithPerson('Emily', 1983, 'Diaz', 'spanish');
2.6 Maps
Before ES6, Object works key-value pairs called a hash map by properties. A map is a new key-value data structure in ES6 and one of the big differences is that in Maps, we can use anything for the keys like numbers, string, or boolean which is primitive while the object was limited string.
There are a couple of reasons that Maps are better than object to create hash maps.
- We can use anything as keys which opens a lot of possibilities
- Maps are iterable
- Easy to get the size of a map using the size property
- We can easily add and remove data from a map
const question = new Map(); // way to add new key-value pair question.set('question', 'What is the official name of the latest major JavaScript version?'); question.set(1, 'ES5'); question.set(2, 'ES6'); question.set(3, 'ES2015'); question.set(4, 'ES7'); question.set('correct', 3); question.set(true, 'Correct answer :D'); question.set(false, 'Wrong, please try again!'); console.log(question.get('question')); // 8 console.log(question.size); if(question.has(4)) { //console.log('Answer 4 is here') // way to delete element question.delete(4); } // clear all elements //question.clear(); // forEach works well with Map question.forEach((value, key) => console.log(`This is ${key}, and it's set to ${value}`)); // using destructing with entries for (let [key, value] of question.entries()) { if (typeof(key) === 'number') { console.log(`Answer ${key}: ${value}`); } } const ans = parseInt(prompt('Write the correct answer')); console.log(question.get(ans === question.get('correct')));
3. References
'DynamicPL > Javascript' 카테고리의 다른 글
Arrow function (0) 2019.10.24 let, const, block scope, function scope and IIFEs (0) 2019.10.24 Bind, Call and Apply (0) 2019.10.24 First-Class Functions and IIFE (0) 2019.10.24 Primitives vs. Objects (0) 2019.10.24