Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to emulate inline let expressions in JavaScript?

Tags:

javascript

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?

like image 258
MaiaVictor Avatar asked Oct 19 '25 14:10

MaiaVictor


1 Answers

No, there is not.

You should consider using the standard lambda calculus technique where let x = … in … is equivalent to (x => …)(…). Then have another pass of your compiler remove the superfluous function expressions, introducing statements where possible.

An alternative might be to use the do { let x = …; … } syntax from the do expressions proposal, allowing you to use their transpiler plugin for generating function-less code.

like image 69
Bergi Avatar answered Oct 21 '25 03:10

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!