An alternative to the block which you ended up with is to extract that logic to a function, which provides something which can be tested too. Possibly overkill for oneliners like this though.
However, writing a lot of code like this myself (get a value, if it's truthy do something, else do other), that's a nice idea for an extension that doesn't add extra variable bindings to the containing scope. On Tue, Sep 13, 2016 at 2:32 AM, Danielle McLean <[email protected]> wrote: > In current ECMAScript, it is legal to place a variable declaration inside > the > initialiser of a `for` loop, as well as to declare the variable used by a > `for...in` or `for...of` loop within the declaring expression: > > for (let i = 0; i < 5; ++i) console.log(i); > for (let item of collection) process(item); > > When this syntax is used with `let` or `const`, the resulting variable is > scoped to the loop and is not visible to the rest of the surrounding block. > > I propose that this syntax be extended, making it legal to place a variable > declaration within the condition of an `if` or `while` statement. Any > truthy > value will cause the `if` block to run or `while` loop to repeat, as usual > - > the advantage is that the particular truthy value is bound to a variable > and > can be used inside the conditional block. For example, here is the > situation > that prompted my writing this proposal: > > if (const oldValue = _.get(object, 'some.long.path')) { > object.some.long.path = transform(oldValue); > } > > As with the existing behaviour of declarations inside `for`, variables > declared > using `let` or `const` would be scoped to the individual `if` or `while` > statement, rather than the containing block. In other words, the above > syntax > would be equivalent to the following currently-valid form I ended up > writing: > > { > const oldValue = _.get(object, 'some.long.path'); > if (oldValue) object.some.long.path = transform(oldValue); > } > > Another use case which C aficianados might recognise: > > while (const c = getchar()) { > process(c); > } > > This syntax is already legal in C++, although not in C - in general this > support is known as "anaphoric if", as it allows the body of the statement > to > refer back to the condition value. It's especially helpful in languages > with > truthiness, which ECMAScript has, as it allows access to the *specific* > truthy > value without further finagling. > > Thoughts? > _______________________________________________ > es-discuss mailing list > [email protected] > https://mail.mozilla.org/listinfo/es-discuss > -- Dan Peddle *tel*: +49 157 3918 2066 *email*: [email protected] *www*: http://flarework.com *in*: http://pt.linkedin.com/in/danpeddle
_______________________________________________ es-discuss mailing list [email protected] https://mail.mozilla.org/listinfo/es-discuss

