Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node v6 failing on object spread

People also ask

Can Spread operator be used on object?

Spread syntax can be used when all elements from an object or array need to be included in a new array or object, or should be applied one-by-one in a function call's arguments list.

Is object assign same as spread?

The difference is that Object. assign changes the object in-place, while the spread operator ( ... ) creates a brand new object, and this will break object reference equality.

How do you update an object using the spread operator?

To use the spread operator to update an object value with JavaScript, we use the spread operator in a new object. const o2 = { ... o1, a: "updated a" }; console. log(o2);

Can I use spread operator in node JS?

The spread operator can be applied to structures like arrays, string and objects.


Using rest/spread with objects is a separate proposal, which you can read about here. A proposal doesn't get accepted for the yearly ES release unless it reaches stage 4, and it is currently stage 3. It may make it into ES2018. If you want to use it now, you'll have to use a transpiler like babel.


EDIT: As of Node v8.3, object rest/spread is available without the need for any transpilation.


Looks like ES6 spread operator only works for arrays and iterables. It is specifically designed to NOT WORK for objects: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator

Relevant quote:

Only apply for iterables

var obj = {"key1":"value1"};
function myFunction(x) {
    console.log(x); // undefined
}
myFunction(...obj);
var args = [...obj];
console.log(args, args.length) //[] 0

Though the MDN article previously suggested that trying to use the spread operator on objects should result in undefined instead of throwing an error. As of this revision, the current MDN article discusses support for "Spread for object literals"

Additionally the node.js compatibility table claims node.js fully comply with the specification of the spread operator with arrays and iterables, but specifically indicates that object rest/spread properties are not supported: http://node.green/#ESNEXT-candidate--stage-3--object-rest-spread-properties, at least not until Node version 8.60 (at which point the color turns green to indicate that beginning in 8.3, Node does support the object spread/rest operator, as pointed out in the other answer)