EDDYMENS

Published 2 years ago

Javascript Assignment Deconstruction - A Good Use Case

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]; 03: 04: console.log(a); // 10 05: 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; 03: 04: // While there remain elements to shuffle. 05: while (currentIndex != 0) { 06: 07: // Pick a remaining element. 08: randomIndex = Math.floor(Math.random() * currentIndex); 09: currentIndex--; 10: 11: // And swap it with the current element. 12: [array[currentIndex], array[randomIndex]] = 13: [array[randomIndex], array[currentIndex]]; 14: } 15: 16: return array; 17: } 18: 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 😊 Knowing when it's a Model or a Builder(Laravel)