# Counting iterations when using Google Earth Engine function .iterate()

I am writing a function that iterates over a list of numbers in GEE, and I would like to count which iteration the function is currently in since I need it to run other calculations. However, I haven't found the way of doing so. Trying the classical approach (i.e. j=j+1) returns a false result. The code example is below:

``````var j = ee.Number(0);

var test = ee.List([10,42,5,1,78,6]).iterate(function(i,list){
var accum = ee.Number(i).add(ee.List(list).get(-1))
},ee.List());

print(test);
print(j);
``````

The code print the final j as 3 when there clearly are 6 elements in the list.

You can't modify global variables in an iterated or mapped function.

The simpler way is to iterate over the indexes, not the list.

``````list = ee.List([10,42,5,1,78,6])
test = ee.List.sequence(0, list.size()).iterate(function(index, result) {
...
})
``````

That said, it's generally better to avoid iterate() if possible, since it doesn't scale well.

Figured it out, it's a bit convoluted but I think there is no other way, the way of getting the current iteration is (in this case) `ee.List([10,42,5,1,78,6]).indexOf(i)`