1

I am running the following code in a browser console and also with node.js v9.11.1 in the terminal:

let name = {};
Object.defineProperty(name, 'last', {value: 'Doe'});
console.log(name);

The browser console works properly and outputs { last: 'Doe' }. But in the terminal with node.js, it fails and outputs a blank object, {}.

What could be the issue here?

John Mutuma
  • 3,150
  • 2
  • 18
  • 31

1 Answers1

12

One of the properties of property descriptors is enumerable, which has the default value false. If a property is non-enumerable, Node.js chooses not to display the property, thats it.

You can change that bit and try this

let name = {};
Object.defineProperty(name, 'last', {
  value: 'Doe',
  enumerable: true
});
console.log(name);
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • 1
    i was typing this as the answer came up heh. yes. youll notice if you repl without setting `enumerable` to true, you can `console.log(name.last)` and it will output 'Doe' as expected in node. – James LeClair Jun 20 '18 at 14:58
  • Wonderful! These are all great responses. My desire was to use the object with the `Spread operator` like `{...name}` in one of my operations. So the `enumerable: true` bit has sorted me out. Thank you @thefourtheye and @James LeClair! – John Mutuma Jun 20 '18 at 15:25
  • @JohnMutuma: FWIW, [`...` is not an operator.](https://stackoverflow.com/questions/37151966/what-is-spreadelement-in-ecmascript-documentation-is-it-the-same-as-spread-oper/37152508#37152508) – Felix Kling Jun 20 '18 at 20:55