3 ms·
the one thing that annoys me about let/const that leads to me occasionally using var is that with var you can declare a variable in a try block and then use it
by cwmma 7y ago
the one thing that annoys me about let/const that leads to me occasionally using var is that with var you can declare a variable in a try block and then use it afterwards, instead I have to declare a let outside the try or put way more then I want to in the try.
- dragonwriter 7y agoBut, why would you want the declaration in the try when the scope of the variable is broader? It's true that var let's you do that, but it seems to me that's strictly a misleading thing. Sure, you’ll often need to split declaration from assignment with let in that case, but that's not a bad thing, IME.
- madacol 7y agotry { const { attribute1, attribute2 } = getObject() } catch () {} attribute1 // undefined How would you solve that?
- dragonwriter 7y agoWith let outside the try, because that's the intended scope. Insofar as there is a problem I see with that, it's that you can't separate declaration of a single-assignment value (const) from the one allowed assignment, because the ideal solution would be const declared outside the try with the assignment inside. OTOH var declared inside is a bad solution because it's both misleading as to scope and using a freely-assignable variable for something that's logically single-assignment. Let outside has only one of those problems.
- madacol 7y agoExactly, I'm just pointing out the limitations of `let/const` I usually solve that case with let attribute1, attribute2; try { const object = getObject() attribute1 = object.attribute1 attribute2 = object.attribute2 } catch () {} But I'm just not satisfied with it, too many statements. And it gets really messy with many attributes
- decentralised 7y agoHow about this: let attribute1, attribute2; try { ({attribute1, attribute2} = getObject()) } catch (e) {}
- madacol 7y agowow, didn't know that! So parenthesis are the trick, thanks!
- decentralised 7y agoNo problem!
- ht85 7y agoIt would be nice if you could assign the result of a try / catch (or any block) to a variable, you can kind of emulate it with an IIFE: const outer = (() => { try { ... return ... } catch (error) { ... } })()
- mschuetz 7y agoThat may be a nice addition to the "do expression" proposal for javascript: https://github.com/tc39/proposal-do-expressions https://github.com/tc39/proposal-do-expressions let x = do { let tmp = f(); tmp * tmp + 1 }; Unfortunately it seems like the proposal doesn't get much attention.
- eyelidlessness 7y agoIt would be nice if every JS statement had an expression equivalent.