Note: I am using an extension in VS Code (the code editor in the screenshots) called Quokka, which shows the instantaneous values of variable inline. You can verify the values using console.log() statements.[/vc_column_text][/vc_column][/vc_row][vc_row][vc_column width=”1/2″][vc_column_text]There are multiple ways to fix/avoid this bug, let us take a look at two of them.
- Using the slice function. The slice() function on an array returns a shallow copy of a portion of the array into a new array object. The original array will not be modified. If we don’t provide any arguments, the whole array is copied into a new array object. Thus changing one array will not affect the other.
- Using the spread operator. The spread operator (…) was introduced in ES6 specification. Using this you can insert all the values (i.e. spread the array) in a particular place.
Example of both is shown in the adjacent screenshot, and values verified using the Quokka extension.[/vc_column_text][/vc_column][vc_column width=”1/2″][vc_single_image image=”1126″ img_size=”full” onclick=”link_image”][/vc_column][/vc_row][vc_row][vc_column][vc_column_text]As we can see, the copies array2 and array3 are no longer affected by sorting array1, because these are entirely new objects in memory rather than being a reference to the old one. For someone who doesn’t have proper understanding of the concept of pointers and references, this kind of bugs will creep into their high-level-language programs and they will find it very difficult to understand and debug them.
A practical scenario may arise in the sorting visualization shown below. Its embedded in an iframe below, but you can view the actual page here. To correctly compare the time taken by different sorting algorithm, we need to keep a copy of the unsorted array every time we use a sorting algorithm on the original array.[/vc_column_text][vc_column_text]
If you liked this article please comment and show your support and interest so that I’ll be motivated to continue this effort. Like our facebook page if you haven’t already. And if you have any questions please comment. I’ll try to reply all.[/vc_column_text][/vc_column][/vc_row]