0

Why does logging an object that has a property assigned to it not show in the console?

const object1 = {};

Object.defineProperty(object1, 'property1', {
  value: 42,
  writable: false});


object1.property1 = 77;
// Throws an error in strict mode

console.log(object1);
// Expected output: {'property1': 42}

console.log(object1.property1)
Oguzcan
  • 412
  • 6
  • 20

1 Answers1

2

Most likely because the console you're using uses something like JSON.stringify() or for...in to create the logging display for its objects (for example, the stack-snippets console uses for...in to create its stringified object). The JSON.stringify() method and many looping methods such as for...in will skip properties that aren't enumerable. By default, when using defineProperty() to create a new property, the property is automatically set as enumerable: false. Instead, if you define it explicitly as true, you'll see it appear as expected:

const object1 = {};

Object.defineProperty(object1, 'property1', {
  value: 42,
  writable: false,
  enumerable: true // explicitly state that the property is enumerable
});


object1.property1 = 77;
// Throws an error in strict mode

console.log(object1);
// Expected output: {'property1': 42}

console.log(object1.property1)
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64