I'm writing a compiler from a functional language to JavaScript. Since my language is based on expressions, it is natural to compile it to a JavaScript expression too. The problem is that when compiling let
expressions, we need the ability to declare and assign variables "inline". For example:
function foo(x) {
return (let y = x * x; y);
}
This code, obviously, doesn't work since we can't use let
inside expressions. One solution would be to wrap everything inside a lambda:
function foo(x) {
return (()=>{let y = x*x; return y})();
}
But this has a significant runtime cost in some cases. The other alternative would be to just adjust the compiler to produce statements instead of expressions, but this would be a non-trivial change and I'd rather avoid it if possible.
Is there any way to declare and assign local variables to JavaScript as an expression rather than a statement that has no extra runtime costs?