Spread Operator and Destructuring
ES6 introduces the spread operator, which allows to expand array and other expressions in places where multiple parameters or elements are expected.
ES5 code
var arr = [6, 89, 3, 45];var maximus = Math.max.apply(null, arr);console.log(maximus)
89ES6 code. (Math.max(arr) return NaN. spread operator makes this syntax much better to read and maintain.
var arr = [6, 89, 3, 45];
var maximus = Math.max(...arr);
console.log(maximus)
89Destructuring Assigment to Extract values from Objects
Introduced Destructuring assigment in ES6. it Assign values taken directly from an object.
ES5 Code
ES6 codeconst user = { name: 'Shreyash Kolhe', age: 21 };const name = user.name;const age = user.age;
const {name, age} = user;
Desructuring allows you to assign a new variable name when extracting values. You can do this by putting the new name after a colon when assigning the value.
const user = {name: 'shreyash', age: 21};console.log(user)
{name: 'shreyash', age: 21}Here's how you can give new variable names in the assignement.
const profile = {name : 'shreyash',age : 21}const { name: userName, age: userAge } = profile;console.log(userName)console.log(userAge)
shreyash 21Destructuring Assignement to Assign Variable from nested Objects.
const profile = {fy : {name:'shreyash', age:19},sy : {name : 'vaibhav', age:20},ty : {name : 'changu', age: 21}};const {sy : { name: newName, age: newAge}} = profile;
ES6 makes destructuring arrays is easy like destructuring objects.
// array Destructuringconst [a, b] = [1,2];console.log(a, b)
1 2
// array rest parameter destructuringconst [a1,b1, ...arr] = [1,2,3,4,5];console.log(a1,b1)console.log(arr)
1 2 [ 3, 4, 5 ]Destructuring Assignment to pass an objects as a function's parameters.
const markes = {nodejs: 89,angular: 80,reactJs: 99}const total = ({ nodejs, angular, reactJs }) => (nodejs + angular + reactJs)/3;console.log (markes)console.log(total(markes))
{ nodejs: 89, angular: 80, reactJs: 99 } 89.33333333333333
Post a Comment