tc39 / proposal-logical-assignment

A proposal to combine Logical Operators and Assignment Expressions
https://tc39.es/proposal-logical-assignment/
MIT License
301 stars 13 forks source link

Better examples? #22

Open slorber opened 4 years ago

slorber commented 4 years ago

Hi,

@DanielRosenwasser suggested I open an issue here to discuss better examples.

https://twitter.com/drosenwasser/status/1245995703559532544

Currently exemples feels a bit bad to me, because they show potentially dangerous side-effectful functions

image

Here it's not harmful because the example({ foo: 'foo' }) is passed a new option object everytime, but with example(constantObject) and having the constantObject being shared could be very dangerous, as it could somehow override default option values or things like that.


I don't have a good example to suggest.

Could people that want the feature can come with beter real world code where this new proposal would actually improve the program.

I'm willing to get convinced by this proposal, and wanted to check examples for that, but it didn't really help so far (somehow, related to https://github.com/tc39/proposal-logical-assignment/issues/2)

jridgewell commented 4 years ago

Thanks for opening! You're right, we do need better examples. Common uses I've seen are:

  1. https://github.com/ampproject/amphtml/blob/303f48924029522c36f1b25dd7319d82d67b75ba/src/preact/base-element.js#L311-L312
  2. https://docs.google.com/presentation/d/1XbYMm7IkHef6hpvwQlLSxb_b5gSkf1g6iuNL9WM0DQ8/edit#slide=id.g7d4f60d66a_1_5
  3. https://github.com/ampproject/amphtml/blob/303f48924029522c36f1b25dd7319d82d67b75ba/src/observable.js#L37-L39

The examples in the readme were super contrived, just meant to give an example of the syntax. What I commonly want it for are to lazy init properties on class instances. And sometimes to initialize properties deeply owned by my instances.

slorber commented 4 years ago

Thanks for these examples.

Honestly these didn't really convince me much.

const list = name == 'children' ? children : props[name] || (props[name] = []);
const list = name == 'children' ? children : props[name] ||= []);

I'd say in both cases it's not very readable, and you can probably be rewritten it in a more understandable way that would not require logical assignment operators in the first place.

GrosSacASac commented 4 years ago

Hi, I saw on reddit that the very first example is not self explanatory. Not everyone is familiar with a || (a = b); kind of syntax. Maybe try something more universal like if else.