If statement expression alias

In many cases, we create disposable variables out of scope to prevent duplicate executions.

const result = expensiveCalculation(); // result = 0.85
if (result > 0.5) {
    // ...
} else if (result > 0.6) {
    // ...
} else {
    // ...
}
// result is accessible out here!

Right now this can be delegated to a function to create a scope, or even additional blocks added as layers, but not everyone wants to (or can) break all of their flow into functions.

if (true) {
    // insert above code... not ideal
}

/* OR */

function normalFlow() {
    // other stuff
    expensiveCalculationLogicWrapper(); // also not ideal (in all scenarios)
    // other stuff
}

To keep scope private, a similar syntax to Go could be introduced.[0]
[0] https://golang.org/ref/spec#If_statements

if (let result = expensiveCalculation(); result > 0.5) { ... }
/* OR */
if (expensiveCalculation() as result > 0.5) { ... }

Could be let/const, x as y, etc. I am not sure about the syntax at this point since the assignment has to be unambiguous from the expression (although they should not be mutually exclusive.)

if (let result = expensiveCalculation() > 0.5) { ... } // result = boolean

I currently overcome this issue by using a for of loop as a wrapper, but it's definitely not semantic:

for (const result of [expensiveCalculation()]) {
    // operate on `result`
    // wrap as single-item array for iteration. Works but not obvious to the reader.
}

I haven't thought about this past this post, and I might have missed a million things, so feel free to compliment it or shoot it down :)

Regards,
Rafael

1 Like

https://github.com/tc39/proposal-Declarations-in-Conditionals/ may be relevant.

4 Likes

(What @ljharb said). Notice you currently don't need if (true) to introduce a block:

{
    const result = expensiveCalculation(); // result = 0.85
    if (result > 0.5) {
        // ...
    } else if (result > 0.6) {
        // ...
    } else {
        // ...
    }
}
// result is not accessible out here!
1 Like

Thanks @ljharb, missed that when looking through the proposals.

True @bergus, thanks for clarifying. Still not ideal though but that existing proposal will do.