Search code examples
javascriptscopevarlet

JavaScript - Solution of an exercise does not work when using let instead of var


I receive an error when replacing var with let. I suppose that it is related to their different scope but don't know how to modify the code so that it can work with let as well.

var array = [242, 682, 933];

for (var i = 0, sum = 0; i < array.length; sum += array[i++]){
  var b = array[i];
  var x = Math.floor(b/100) % 10;
  var y = Math.floor(b/10) % 10;
  var z = b%10;

  if (x+z!==y) {
    break;
  }
}

console.log (sum);

Solution

  • because let keyword limiting the variable scope more than var does.

    check this : let on MDN

    If you want to access the sum outside of the loops block, you also have to declare it outside:

    var array = [242, 682, 933];
    let sum = 0; // <-- declaration in the highest scope
    
    for (let i = 0; i < array.length; ++i){
      let b = array[i];
      let x = Math.floor(b/100) % 10;
      let y = Math.floor(b/10) % 10;
      let z = b%10;
    
      if (x + z !== y) {
        break;
      }
    
    
      sum += array[i];
    }
    
    console.log (sum); // now you can access it here