Your code is returning "unexpected" results because you are mixing client-side Javascript control structures with server-side Earth Engine methods. In general, you should avoid doing this. Review the Earth Engine Client vs. Server docs page for a complete discussion.
For your simple example, you can use an ee.List() object to accumulate values, and later convert it to an ee.Array():
var first = ee.List([1]);
var list = ee.List.sequence(0, 4);
var iter_function = function (num, list){
num = ee.Number(num);
var new_value = num.multiply(num);
return ee.List(list).add(new_value);
};
var resulting_list = list.iterate(iter_function, first);
print('resulting_list', resulting_list);
var resulting_array = ee.Array(resulting_list);
print('resulting_array', resulting_array);
However, if your actual use case is too complex for ee.List() objects, you can iterate using ee.Array() objects:
var first = ee.Array([1]);
var list = ee.List.sequence(0, 4);
var iter_function = function (num, list){
num = ee.Number(num);
var new_value = ee.Array([num.multiply(num)]);
return ee.Array.cat([list, new_value]);
};
var resulting_array = list.iterate(iter_function, first);
print('resulting_array', resulting_array);
If processing each element in your list is independent of the others, you can map your function across this list using ee.List.map() instead:
var list = ee.List.sequence(0, 4);
var map_function = function (num){
num = ee.Number(num);
var new_value = num.multiply(num);
return new_value;
};
var resulting_list = list.map(map_function);
print('resulting_list', resulting_list);
var resulting_array = ee.Array(resulting_list);
print('resulting_array', resulting_array);
The moral of this story is: "Friends don't let friends use loops with big data."