0

I'm currently doing a Javascript bootcamp. Today we were studying Sorting methods. The teacher provided us with "template" not-built-in functions. Another teacher also said that nowadays there's no reason to use VAR anymore to define a variable, that we should always use LET (and const, etc.). So I copypasted his code in VSCode tu run it and study it. Then I decided to change all the VARs for LETs, and the code stopped working. I tried one by one and discovered it is one in particular (inside a loop that is nested in another loop) that if changed, then the code throws an error. So i would like to understand why is this happening? We've used lots of nested loops and this is the first time it happens. Here is the code:

// INSERTION SORT

function insertionSort(arr){
    let currentVal;
    for(let i = 1; i < arr.length; i++){
        currentVal = arr[i];
        for(**var** j = i - 1; j >= 0 && arr[j] > currentVal; j--) { 
            arr[j+1] = arr[j]
        }
        arr[j+1] = currentVal;
    }
    return arr;
}

let hola = insertionSort([26,54,2,1,9,20,99,76,4]);
console.log(hola);

I wonder if this is related to the scope... If I delete this VAR, the code runs with no issue.... what's going on

kelsny
  • 23,009
  • 3
  • 19
  • 48
rubensoon
  • 13
  • 3
  • Did you look at the error message with `let`? `let` has block scope, unlike `var`, which has function scope, and here, you're trying to access `j` outside of the block where it's initialized. – CertainPerformance Nov 04 '22 at 04:40
  • i don't know how to upvote your comment. Thank you! What you said made me think and went back to the code to explore. I think I finally understood what you mean, thank you again! – rubensoon Nov 04 '22 at 12:59

0 Answers0