Object literals
Probably the most popular option for creating objects. When we use this approach all property descriptors will be set to default, true value.
// const tvShow = { name: 'Breaking Bad', seasons: 5, sayHello: function() { console.log('Hello Breaking Bad!'); } } //
Object.create()
The second way gives us more control over the object and its property descriptors like writable, enumerable, configurable, and value.
writable - if set to false we cannot change the property value configurable: if set to false, any attempts to delete or change the property will fail enumerable: if set to false we cannot loop through the object value: value of the property
// const tvShow = Object.create({}, { name: { writable: true, configurable: true, enumerable: true, value: 'Breaking Bad' }, seasons: { writable: false, configurable: false, enumerable: false, value: 5 }, sayHello: { writable: true, configurable: true, enumerable: true, value: function() { console.log('Hello Breaking Bad!')} } }); //
Above we achieved the same result as creating object using Object literals. The difference is, that the property “seasons” has writable, configurable and enumerable set to false. We cannot reconfigure this object, we cannot delete “seasons” property, we cannot change its value and in for loop this property won’t be visible.
// tvShows.seasons = 10; console.log(tvShows.seasons); // still 5 delete tvShows.seasons //Error, because configurable is set to false for(data in tvShow) { console.log(data); //name //sayHello - we won't see seasons property - enumerable set to false } console.log(Object.values(tvShow)); //we won't see value of the season property - enumerable set to false console.log(Object.keys(tvShow)); //we won't the key of the season property - enumerable set to false //
Summary
If we want in some cases to have more control over an object’s property descriptors we should choose creating object using create() method approach.