Javascript Assignment Deconstruction - A Good Use Case

Stripe Integration Freelance Gig external link
🔗 See other jobs

The Javascript assignment deconstruction syntax simplifies taking values in an array or object and storing each item as individual variables.

01: var a, b;
02: [a, b] = [10, 20];
04: console.log(a); // 10
06: console.log(b); //20

The values don't necessarily have to be stored in variables, they can be stored as a new array, object, or even back to the original array or object variable.

Thinking outside of the general idea of using deconstructors to create variables leads to a very good use case, which is the ability to reorganize data in a given array or object, to randomize them for example.

01: function shuffle(array) {
02:   let currentIndex = array.length,  randomIndex;
04:   // While there remain elements to shuffle.
05:   while (currentIndex != 0) {
07:     // Pick a remaining element.
08:     randomIndex = Math.floor(Math.random() * currentIndex);
09:     currentIndex--;
11:     // And swap it with the current element.
12:     [array[currentIndex], array[randomIndex]] = 
13:     [array[randomIndex], array[currentIndex]];
14:   }
16:   return array;
17: }
19: // Used like so
20: var arr = [2, 11, 37, 42];
21: shuffle(arr);
22: console.log(arr);

I found the above code while scouting StackOverflow. I noticed the use of the deconstructor pattern on line 12.

The author of the code swaps the array values using the currentIndex value which is the index generated based on the loop. Then to pick a random location to store the selected value, it uses the random number generated on line 08 randomIndex.

The deconstructor helps to reassign those values to different positions within the same array.

Here is another article you might like 😊 "What to watch out for when writing JavaScript without semi-colons"