3 ms·
Yes, I'm very excited about the spread operator! I've been spoiled by Firefox.
by cmpb 11y ago
Yes, I'm very excited about the spread operator! I've been spoiled by Firefox.
- rplnt 11y agoLooking at documentation.. does this only work on lists (or list like object)? I.e. you can't "expand" a k:w object? Or is there another operator for this? Example: function foo(a=1, b=2, c=3) { return a * b * c;} dict = {'b': 4, 'c': 6}; foo(...dict);
- arcatek 11y agoYes and no. You can still do something like: foo(... Object.keys(dict).map(name => dict[name])) (Maybe someday you might be able to use Object.values() to achieve the exact same thing without needing to use .map) However, the spread operator doesn't match the argument names to the object names. So the above call would mean the following: foo(4, 6) And not what you'd like: foo(undefined, 4, 6) However, note that you can rest an object too: let x = { a : 1, b : 2, c : 3 }; let { a, ... rest } = x; console.log( ... rest ); // { b : 2, c : 3 }
- cmpb 11y agoTechnically, the spread operator works with iterables [1]. If you wanted to spread an object `obj`you'd need to define `obj[Symbol.iterator]` [2]. [1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... [2] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- moretti 11y agoYou still have to simulate named arguments with an object: const foo = ({ a = 2, b = 2, c = 3 } = {}) => a * b * c; const dict = {b: 4, c: 6}; foo(); // 12 foo(dict); // 48