6 ms·
Have been using the spread operator via Babel for several months now. It's definitely convenient - saving me from writing several extra lines of code. I worry
by a13n 9y ago
Have been using the spread operator via Babel for several months now. It's definitely convenient - saving me from writing several extra lines of code.
I worry that spread operators make code less readable. You really have to squint and think more when confronted with one.
They also make your code less understandable to a beginner, or people coming from other languages.
One of my favorite ways to use them:
const foo = {};
if (bar) {
foo.bar = bar;
}
Turns into:
const foo = {
...bar && {bar},
};
- STRML 9y agoSome parens would at least make that more readable: const foo = { ...(bar && {bar}), };
- masklinn 9y ago… Wouldn't const foo = bar ? {bar} : {}; be both more efficient and more readable?
- a13n 9y agoWell typically there are more parameters being set than just the one.
- Demiurge 9y agoThat's a good example of Abad use of the feature. The logical check and assignment are obvious, and represent the same two operation that three or more nested operations in spread and combine end up causing implicitly. If I saw anyone do that at work, I'd have a chat with them. This is on the same level the newlinephobia.
- koblas 9y agoWarning; a few weeks ago I ended up in a debate with a co-worker and ran the performance tests on this construct. Turns out that you would be better served by ```foo.bar = bar``` since nodejs doesn't give you the performance you expect.
- rmrfrmrf 9y agoNot nearly as abusive as const obj = { foo: 1, bar: 2 }; const propToDelete = "foo"; { [propToDelete]: _, ...newObj } = obj; newObj; // { bar: 2 } but will probably be more performant than `delete` in the long run.
- rk06 9y agoWhy? if you really want to write shorter code, try const foo = {}; foo.bar = bar ||undefined;