Re:JavaScript variables: var and let and const
by madacol on Friday March 06, 2020 @06:24PM
(#22508340)
try {
const { attribute1, attribute2 } = getObject()
} catch () {}
attribute1 // undefined
How would you solve that?
Re:JavaScript variables: var and let and const
by dragonwriter on Friday March 06, 2020 @10:34PM
(#22509557)
With 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.
Re:JavaScript variables: var and let and const
by madacol on Saturday March 07, 2020 @08:56AM
(#22511539)
Exactly, 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
Re:JavaScript variables: var and let and const
by decentralised on Sunday March 08, 2020 @08:31AM
(#22517704)
How about this:
let attribute1, attribute2;
try {
({attribute1, attribute2} = getObject())
} catch (e) {}
Re:JavaScript variables: var and let and const
by madacol on Sunday March 08, 2020 @09:38PM
(#22522155)
wow, didn't know that!
So parenthesis are the trick, thanks!
Re:JavaScript variables: var and let and const
by decentralised on Monday March 09, 2020 @03:28AM
(#22523603)
No problem!
Sure, you’ll often need to split declaration from assignment with let in that case, but that's not a bad thing, IME.