DEV Community

Discussion on: Do You Still Use Var? If So Why?

Collapse
 
karataev profile image
Eugene Karataev

Why is it necessary to use var instead of let in your example? You don't access stuff variable in catch block anyway.

Collapse
 
vonheikemen profile image
Heiker

But I want to use it outside the try/catch block.

Thread Thread
 
karataev profile image
Eugene Karataev

Just define it in the parent scope. It has extra line if compare with var, but I think this code is more obvious, because there is no implicit hoisting.

async function foo() {
  let stuff;
  try {
    stuff = await unsafe_stuff();
  } catch (err) {
    return Promise.reject(err.message);
  }
  console.log(stuff);
}
Thread Thread
 
vonheikemen profile image
Heiker

That is what I'm trying to avoid. And you could still do the same with var.

I choose to believe var's implicit hoisting is a feature and not a bug.

Thread Thread
 
karataev profile image
Eugene Karataev

I agree, this is a valid use case for var if you prefer implicit hoisting.