4 ms·
It's funny how the language you primarily work with changes your perspective. JavaScript supports "object spreading", which lets you do this: let foo = { x:
by _bxg1 8y ago
It's funny how the language you primarily work with changes your perspective.
JavaScript supports "object spreading", which lets you do this:
let foo = { x: 1, y: 2 };
...
let { x, y } = foo;
console.log(x + y); // 3
A common pattern is to use this as a stand-in for named/unordered function arguments:
function bar({ x, y }) {
return x + y;
}
bar({ x: 3, y: 4 });
// or...
let foo = { x: 1, y: 2 };
bar(foo);
Which is pretty much exactly the "epiphany" at the bottom (the interchangeability of these two). I don't mean to diminish the author's thought process; I just think it's fascinating how different programming languages (even ones so similar in syntax) dramatically shape the way one thinks about a given problem.
- Waterluvian 8y agoSpeaking of language perspective. I see obj spread in JS for arguments as an ugly hack to make up for the lack of named and optional args. It gets really ugly when you attempt to set defaults. My perspective is from Python, which I think gets it very right.
- adrianratnapala 8y agoBut named-args in Python are also syntactic sugar for passing dictionaries around. Object-unpacking of the the kind described here is another one.
- Waterluvian 8y agoSyntactic sugar is the important part here. You can always pass an object and handle defaults and default merging within the function body, sure. I use JavaScript a ton and I do love object spread and array destructuring. But writing function signatures is still very clumsy.
- namelosw 8y agoThere is optional args for JS. And it's not hack since it's a partial form of pattern matching. Although simple and consice is absolutely not JS is famous for, a lot of functional programming languages with consice design do the same thing.
- bfrydl 8y agoThat's actually object destructuring. Object spreading is where you “spread“ an object's keys and values into a new object literal: const foo = { x: 1, y: 2 }; const bar = { ...foo, z: 3 }; // has x, y, and z