6

I'm trying to spread the Javascript Error object(Standard built-in objects). I'm getting the empty object as output.

let error = new Error('error');
console.log({...error});

output:

{}

What is the reason for not spreading the Error object?

mr93
  • 123
  • 2
  • 9
  • What is the expected output? – JJWesterkamp Nov 06 '18 at 06:57
  • Can't believe I don't find a dupe.. If someone has it, let me know. – Kaiido Nov 06 '18 at 07:09
  • [Spread syntax readout : Only for iterables.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Only_for_iterables) – Jai Nov 06 '18 at 07:26
  • @Kaiido You might remember https://meta.stackoverflow.com/q/370046/1048572? – Bergi Nov 06 '18 at 07:27
  • @Bergi, no I didn't remember a question in particular, just found very unlikely that it hadn't been asked already (well actually [I saw one already](https://stackoverflow.com/questions/49103692/using-es6-spread-operator-on-file-object), but even then didn't answered thinking there must be a dupe, that I probably didn't have time to search back then). – Kaiido Nov 06 '18 at 07:31

1 Answers1

10

This is because the spread syntax in object literals "copies own enumerable properties from a provided object onto a new object".

None of the own properties of your Error object are enumerable.

var error = new Error('error');
var props = Object.getOwnPropertyDescriptors(error);
console.log(props); // none of these are enumerable

So the spread syntax copies nothing. If it had an enumerable value, then it would have copied it:

var error = new Error('error');
error.foo = 'bar';
console.log({...error});
Kaiido
  • 123,334
  • 13
  • 219
  • 285