Destructuring Assignment with Array in ECMAScript

Create new Javascript file named demo1.js. This file contains code demo as below:

let [firstName, middleName, lastName] = ['John', 'Thomas', 'Smith'];
console.log('First Name: ' + firstName);
console.log('Middle Name: ' + middleName);
console.log('Last Name: ' + lastName);

Use node demo1.js statement run code demo

First Name: John
Middle Name: Thomas
Last Name: Smith




Create new Javascript file named demo2.js. This file contains code demo as below:

let [, , lastName] = ['John', 'Thomas', 'Smith'];
console.log('Last Name: ' + lastName);

Use node demo2.js statement run code demo

Last Name: Smith

Create new Javascript file named demo3.js. This file contains code demo as below:

let firstName, middleName, lastName;
[firstName, middleName, lastName] = ['John', 'Thomas', 'Smith'];
console.log('First Name: ' + firstName);
console.log('Middle Name: ' + middleName);
console.log('Last Name: ' + lastName);

Use node demo3.js statement run code demo

First Name: John
Middle Name: Thomas
Last Name: Smith




Create new Javascript file named demo4.js. This file contains code demo as below:

let [firstName, ...rest] = ['John', 'Thomas', 'Smith'];
console.log('First Name: ' + firstName);
console.log('Rest: ' + rest);

Use node demo4.js statement run code demo

First Name: John
Rest: Thomas,Smith

Create new Javascript file named demo5.js. This file contains code demo as below:

let [name = "Guest", surname = "Anonymous"] = ["Julius"];
console.log('Name: ' + name);
console.log('Surname: ' + surname);

Use node demo5.js statement run code demo

Name: Julius
Surname: Anonymous