statement reuse inside if

Good evening, I am working with goland and would like to know if an if check could be added. that you can use a variable defined within it if. it would be like an if line an idea would be this example of a simple return function

maybe it is impossible to do it but it will save a lot of code in large projects

async function boom() {
     return { statusCode: 'success', data: [] }
}

if (let x = await boom() & x.statusCode === 'success' & ... /* conditions**/) {
    console.log(x) 
}

You can already use top-level await in ES Modules; to use let/const like that inside an if, see GitHub - tc39/proposal-Declarations-in-Conditionals

1 Like

Hi @njavilas2015

If await boom() threw an exception, would you expect that to be treated as false by the if, or would the exception continue to bubble?

i.e: what would you expect the following to log?

function bang() { throw new Error() }

try {
  if (let x = bang()) {
    console.log("a");
  } else {
    console.log("b");
  }
} catch {
  console.log("c");
}

it'd have to be the same thing as if (bang()), no?

async function boom() {
    return { statusCode: 'success', data: [] }
}

if (let x = await boom() & x.statusCode === 'success') {
 
    for (let i of x.data) {

    }

    return { statusCode: 'success', data: raw }
}

throw { statusCode: 'error', message: 'Internal Error' }


I have seen this code fragment and it would be the same but inside the if you can use x and y

and in case of exception the catch is executed

Yeah that would be my intuition too. I was just curious what others would assume, maybe another language does use that pattern for error management too?

I am working on a stream platform where we are with go and js. And with go it is less verbose instead with js you have to declare the function store it in a variable and then validate its output something that in go is on the same line and now a few lines this in a microservice would save us about 300 lines of code in a 900 system nearly a third