COMMUNITY

Array comprehension if statement with Void

Hej all,

Nice to see the forum again :slight_smile:

I don’t know if it’s considered as an Array comprehension, I wonder if we can have something like if statement inside an Array with Void.
I mean somethin like that :

var a = [
1, 
2,
if ( condition ) 3,
4
];

With if (condition ) 3 else somethingElse it works but I would have Void, nothing at the place…

Void is not a “type” in the way that you think it is. See Void in the Manual.

That’s why that expression won’t compile because if the condition cannot be met it expects some other value, but that has to be explicit and I don’t think having inferred returns from non-explicit conditions wrapped like that is necessary and could produce problems outside of that context.

A function that always returns a value I think is a reasonable solution and I wouldn’t expect anything more than that.

Thanks for your reply, I know it’s not going to work like that, I just ask if there is a way to have that as we have Array comprehension with for statement. I know for statement gives always an expression and it’s not the same, but it would be cool to have something like that as a shortcut as the Array comprehension does to be fast to write.
For now i can d something like that :

var a = [
1, 
2,
condition ? 3 : null,
4
].filter(i->i!=null);

But it’s still too long for me, I’m too lazy. But not as lazy to not write a good topic like this one to celebrate forum rebirth ! :rofl:

1 Like