Chris Barrett
Chris Barrett

Reputation: 601

Reset variable inside loop

Apologies for how fundamental this question is but I can't find a definitive answer.

I have some code where I was relying on a re-declaration to reset a variable but it seems it doesn't work like I expected. Boiled down I have

for (i=0; i<5; i++){
  var j;
  j += i
}

Clearly pointless code but i though j would be reset on each loop but its just skipped. Is there another way to do this or do I just need to assign it as null?

Cheers

Upvotes: 2

Views: 5711

Answers (2)

Diego
Diego

Reputation: 9571

As mentioned by Chris G, your example doesn't actually apply because the value will always be NaN. Declaring a variable without assigning a value will always make it undefined.

function test() {
  var j;
  Logger.log(j); // undefined
}

If you assign a value, even if that value is null, then you'll be fine. (JS will interpret null as zero... you can read a bit more here.)

function test() {
  for (var i = 0; i < 5; i++){
    var j = null;
    j = j + i; // Explicitly writing to j
    Logger.log(j); // 0.0, 1.0, 2.0, 3.0, 4.0
    Logger.log(j += i); // 0.0, 1.0, 2.0, 3.0, 4.0
  }
}

As indicated by Keith, you could use const, too. That would declare a constant value, so it doesn't require resetting, but you also wouldn't be able to manipulate it.

function test() {
  const j = null;
  for (var i = 0; i < 5; i++){
    j = j + i; // Explicitly writing to j
    Logger.log(j); // null, null, null, null, null
    Logger.log(j += i); // 0.0, 1.0, 2.0, 3.0, 4.0
  }
}

Unfortunately, you can't use let in Google Apps Script.

Upvotes: 0

Ted
Ted

Reputation: 4067

There are more than on problems with your code.

for (i=0; i<5; i++) {
  var j;
  j += i
}
  1. j is a local variable to the for loop, so you won't be able to use its value outside of the loop,
  2. j is not initialised so NaN += i will result to NaN

Change your code to something like this:

var j = 0; // declare the variable outside of the loop and give it an initial value
for (i=0; i<5; i++) {
  j += i;
}
// use j's value somewhere else
var x = j;

Upvotes: 1

Related Questions