0

"while" vs "for" statements in Console

The following code:
let total := 0;
for x from 1 to 5 do
    total := total + 1;
    total;
end

produces the following ouput:
1
2
3
4

For each cicle total is returned.

Similar code with a "while" statment instead of a "for", returns nothing:

let total := 0;
let x := 1 ;
while x < 5 do
    total := total + 1;
    x := x + 1;
    total;
end

1. Question
Any ideia why?

2. Complaint
Console is the best place to test our code before inserting it into formula fields and triggers.
Among other things, there should be a print_console(any_argument_here) statment to allow us to print whatever we need from any point of our code in Console for testing purposes.
Without this it is really hard to develop code and test it.
Don't you agree?

3 replies

null
    • Sean
    • 4 yrs ago
    • Reported - view

    It's not just the Console. The same thing happens in a Formula field. I have no meaningful answer for why they are different only an observation of the difference...

     

    The for-loop will return an iterative value from within the loop. I thought it was an array, but using the item() function after the loop doesn't yield a result. If you add the variable after the loop completes you get the last iterative value.

     

    The while-loop will only deliver a value after the loop completes. It will be the final iterative value unless you concatenate the iterations inside the loop.

    • JGM
    • Jose_Monteiro
    • 4 yrs ago
    • Reported - view

    There is a little trick I use to understand what is being returned.

    It is to enclose whatever data type I want to know about as an argument of a nonexistent function.

    In the above case writing:
    type(total);

    We get the error message:
    Function is not definied: type(number) at line 4, column 16
    Which means a number is being returned.

    The function name could be type() or any other that is not defined, for instance only p().

    The error message, in parenthesis, tells us the data type that is being returned.
    In this case is just a number.
    If what is being returned is an array we would get the message in square brackets, as the following:

    Function is not defined: type([date]) at line 4, column 8
    Which means an array of dates is being returned.

    Thanks.

    • JGM
    • Jose_Monteiro
    • 4 yrs ago
    • Reported - view

    This little trick could be used not only with what is being returned but with any other variable or statment in any block of code.

Content aside

  • 4 yrs agoLast active
  • 3Replies
  • 1660Views