beepboop
beepboop

Reputation: 65

Why is this for loop iterating only once?

I don't know why this for loop is only iterating once. Just a note, I'm quite new to JavaScript.

function bubbleSort(nums) {
    bubbleSortedArray = nums;
    lenOfBSA = bubbleSortedArray.length;
    for (i = 0; i < lenOfBSA; i++) {
        for (j = 0; j < lenOfBSA - i - 1; j++) {
            if (bubbleSortedArray[j] > bubbleSortedArray[j + 1]) {
                swap(bubbleSortedArray, j, j + 1);
                showSorting(bubbleSortedArray); // when i comment this out and call it elsewhere it works
            }
        }
    }
}

function showSorting(nums) {
    canvasprops = setup();
    cc = canvasprops[0];
    c = canvasprops[1];
    cc.clearRect(0, 0, c.width, c.height);
    cc.fillStyle = "lime";
    cc.fillRect(0, 0, c.width, c.height);

    console.log("updated canvas");

    var x = 0;
    cc.fillStyle = "black";
    for (i = 0; i < nums.length; i++) {
        cc.fillRect(x, c.height, 8, 6 * -nums[i]);
        x = x + 8;
    }
}


function setup() {
    var c = document.getElementById("sort-viewer");
    cc = c.getContext("2d");
    c.setAttribute("width", "800px");
    c.setAttribute("height", "620px");
    return [cc, c];
}

function swap(arr, a, b) {
    temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp;
    console.log("swapped");
}

When I comment showSorting(bubbleSortedArray); out from the nested for loop, and place it at the end of the for loops it works, with the for loops iterating multiple times. However, when it's in the nested for loops, there is only one iteration happening for some reason.

The point here is, I'm trying to draw to the canvas each time, to show the array being sorted (trying to create a visualisation).

Any help would be greatly appreciated!

Upvotes: 0

Views: 98

Answers (1)

Espen
Espen

Reputation: 2576

You are not declaring i. It is then a global variable and used by all iterators. Your showSorting function is changing i, therefore the for loop exits.

for(i = 0;i < 10; i++){
   // here i is global since it is not declared and scoped to the for loop
}

for(var i = 0;i < 10; i++){
   // here i is declared and initilized, and scoped to the current function
}
// which means I can access i here:
console.log(i); // outputs 9

for(let i = 0; i < 10; i++){
   // here i is declared and initilized and scoped to the loop only. i is not accessible outside of this loop.
}

Change your for loops to use let i = 0 instead of i = 0 and it should work.

Upvotes: 4

Related Questions