re: Hoist Your Vars! (Variable Hoisting in JavaScript) VIEW POST


I like to use this in try/catch statements as well as some if cases

some times you just want to go const all the way but when you meet these cases using let doesn't feel attractive and in the end, you still need to declare the let variable.

let result;
try {
  result = "abc" // await getResult();
} catch (err) {
  result = "catch"
// or return result
try {
  var result = "abc" // await getResult()
  // throw new Error('I failed you u.u')
} catch (err) {
  result = "catch"

As with anything in code, as long as you and your team agree to do certain things it's okay. If you don't feel is right or your team doesn't want to go that road you can keep it for yourself


I am curious, why is your variable being mutated in the catch block? that block is for errors


the times I need to do this is to show a default for something
or just ensure there is a valid value returned from the function, most of the time this is used on places where failure is not critical or it's a "top level" UI element function call

I'd say it's kind of fail behind scenes keep the good face up


A good example of when you might want to do this is if it’s a known exception and you are going to hand wave it away.

(async () => {
let result
try {
  // catch network issues
  const response = await fetch('https://example.com')
  // catch non-json data
  const data = await response.json()
  // catch inaccessible object
  result = data.messages
} catch(e) {
  result = { messages: [] }
code of conduct - report abuse