-8

Please, can you explain why my code seems to work with var but not let, snippets are below?

Snippet with var:

function revarr(arr) {
  for (var i = 0; i < arr.length / 2; i++) {
    [arr[i], arr[arr.length - 1 - i]] = [arr[arr.length - 1 - i], arr[i]];
  }
  return arr;
}

console.log(revarr([1, 2, 3]))

Snippet with let:

function revarr(arr) {

  for (let i = 0; i < arr.length / 2; i++) {
    [arr[i], arr[arr.length - 1 - i]] = [arr[arr.length - 1 - i], arr[i]];
  }
  return arr;
}

console.log(revarr([1, 2, 3]))

Thanks for your help.

Andrew Bone
  • 7,092
  • 2
  • 18
  • 33
  • 3
    Possible duplicate of [What's the difference between using "let" and "var" to declare a variable?](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable) – aMJay Mar 22 '18 at 13:09
  • The `let` version *does* work. – Pointy Mar 22 '18 at 13:11
  • Which browser are you using? IE6 ? – Andrew Bone Mar 22 '18 at 13:15
  • ^^ both would not work, because where destruction works, there works `let` as well. – Nina Scholz Mar 22 '18 at 13:17
  • The biggest difference is that in the *let* example the index counter "i" is only scoped for use in the for loop (meaning that if you do `console.log( i )` after the var example you will get 2 but if you do it after the let example you should get something like undefined) – Doug Mar 22 '18 at 13:26

1 Answers1

1

Basically let keyword declare variables that are limited scope to the statement, block or expression on which it is used. var keyword defines variables global or local scope.

If we are trying to console.log(i), after for loop in first function then value will be display in console. But if we are trying to console.log(i) after for loop in second function then we will get "ReferenceError: i is not defined" error in console.

Reason:

  1. In first function variable scope is local because of var keyword, so you can access variable i after for loop.

  2. In second function variable scope is limited because of let keyword, so you can access variable i inside for loop only.

Example:

function revarr(arrV){
    var arr = arrV;
    for(var i=0;i<arr.length/2;i++){
        [arr[i],arr[arr.length-1-i]]=[arr[arr.length-1-i],arr[i]];
    }
    console.log(i); // output
    return arr;
}

function revarr(arrVal){

    for(let i=0;i<arrVal.length/2;i++){
        [arrVal[i],arrVal[arrVal.length-1-i]]=[arrVal[arrVal.length-1-i],arrVal[i]];
        console.log(i); //output
    }
    console.log(i);  //ReferenceError: i is not defined
    return arrVal;

}
Jagdish K
  • 11
  • 4
  • but in the let code we are not doing anything with i after the for loop.After the for loop we are just returning the reversed array. let i is only used inside the for loop where its scope is defined..I am confused? – sunny singh Jun 27 '18 at 14:15