Usage Examples of Destructuring Array in ES6 ECMAScript Typescript
to destruct means to destroy array and objects. in other words, to pull apart
ON THE FOLLOWING CODE, YOU ASSIGN THE VALUES FOR THE employee ARRAY,
EXAMPLE 1 /////////////////////////let employee = ["tom","smith","male"];let [fname,lname,gender] = employee;console.log( fname ); // tomconsole.log( lname ); // smithconsole.log( gender ); // male
NOW THE FOLLOWING CODE, WILL DISPLAY gender AS undefined IN CONSOLE BY REMOVING "male" FROM THE ARRAY DECLARATIONS
EXAMPLE 2 /////////////////////////
let employee = ["tom","smith"];let [fname,lname,gender] = employee;console.log( fname ); // tomconsole.log( lname ); // smithconsole.log( gender ); // undefined
NOTE: once you have desctructed the array, any properties not declared will be destroyed
//ON THIS EXAMPLE WILL SHOW YOU HOW TO NOT DESTROY THE ELEMENT BUT LEAVING IT WITHOUT ANY VALUES
// EXAMPLE 3 ////////////////////////let employee = ["tom","smith","male"]; // added male back againlet [,,gender] = employee; // NOTICE I LEFT THE COMMAS HERE//console.log( fname ); // tom//console.log( lname ); // smithconsole.log( gender ); // male
// USING THE YOU CAN DESTRUCTURE REST OPERATOR help you have a single variable that can contain a group of elements
// EXAMPLE 4 ////////////////////////let employee = ["tom","smith","male"]; // added male back againlet [fname, ...elements] = employee; // NOTICE I LEFT THE COMMAS HEREconsole.log( fname ); // tomconsole.log( elements ); // ["smith", "male"]//console.log( gender ); // male
// YOU CAN ALSO SETUP THE DEFAULT VALUE FOR EACH ELEMENT
// EXAMPLE 5 ////////////////////////let employee = ["tom","smith","female"]; // let [fname, lname,gender="male"] = employee; // declare the gender as maleconsole.log( fname ); // tomconsole.log( lname ); // smithconsole.log( gender ); // will output male instead of female
I learned all this from this video:
ES6 and Typescript Tutorial - 17 - Destructuring Array
https://www.youtube.com/watch?v=ol5sgcMvONU&index=16&list=PLC3y8-rFHvwhI0V5mE9Vu6Nm-nap8EcjV