BoGeo
BoGeo

Reputation: 15

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);

Upvotes: 0

Views: 63

Answers (2)

zym
zym

Reputation: 55

The only problem I see is that when you replace var in your for loop condition, then your variable sum would not be accessible from outside of the for loop so console.log (sum); would give you an error.

Upvotes: 1

Dananjaya Ariyasena
Dananjaya Ariyasena

Reputation: 606

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

Upvotes: 1

Related Questions