Sorting by choice, why it works?

Consider the "sorting by choice" from the book. The code line let length = array.length; in one of the 2 functions displays only part of the array. And with it - all of it.

findSmallestIndex function(array) {
 let smallestElement = array[0]; 
 let smallestIndex = 0; 

 for (let i = 1; i < array.length; i++) {
 if (array[i] < smallestElement) {
 smallestElement = array[i];
 smallestIndex = i;

 return smallestIndex;

function selectionSort(array) {
 let sortedArray = [];
 let length = array.length; // THIS LINE

 for (let i = 0; i < length; i++) {
 // Finds the smallest element in the array
 let smallestIndex = findSmallestIndex(array);
 // Add the smallest element to new array
 sortedArray.push(array.splice(smallestIndex, 1)[0]);

 return sortedArray;

selectionSort([5, 3, 4, 7, 8]);
March 19th 20 at 08:44
1 answer
March 19th 20 at 08:46
not well, if not let length = array.length , then in the function selectionSort() is undefined OR length, OR any length outside of this code

if this is all the code, it is undefined and the loop for (let i = 0; i < length; i++) will never execute even once
I mean that you can write the loop without the introduction of variable length. Then the array will be sorted, but will be only part of the elements. And with the introduction of the variable, the entire array is displayed.
Try to substitute length array.length and print the result of sorting. - candida.Crona commented on March 19th 20 at 08:49
@candida.Crona, Ah, now I understand :)
because array.length is recalculated every time, and they cut it in array.splice(smallestIndex, 1)[0]
and if you pre-save in a variable the number of repetitions of the cycle will be determined in advance - Desiree_Spinka commented on March 19th 20 at 08:52
@candida.Crona, because the length of the array is changed inside the loop - kayden_OKon32 commented on March 19th 20 at 08:55

Find more questions by tags AlgorithmsJavaScript