1

I came across a working code for insertion sort which is as follows:

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

My question is: shouldn't the j in the line:

array[j+1] = curr;

be out of scope? What am I missing here?

Ahmad
  • 12,336
  • 6
  • 48
  • 88
  • It's always better to start a variable with `const` identifier and make it `let` as necessary. `var` scope is function scope. – Sid Nov 14 '18 at 09:12
  • 1
    Possible duplicate of [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Armen Michaeli Nov 14 '18 at 09:28

1 Answers1

1

Declaring javascript variables using var makes the scope of the variable be the bounds of the entire function it is declared inside.

Opposed to let, which restricts the scope to the block it is defined inside.

So, no. It will not be out of scope.

Ahmad
  • 12,336
  • 6
  • 48
  • 88