Memo to self - the many syntaxes for creating Objects in Javascript
Jun 24, 2016
I’m not a Javascript developer, and more than once I’ve got confused over the notation. This is a series of notes I took after watching the Jim Cooper lectures on PluralSight to clarify things.
A brief run down of the many syntaxes:
Option 1 - Object literals, upfront
Option 2 - Object literals, in hindsight
Option 3
Option 4 - ECMAScript
The different syntaxes for creating Objects are all syntactical sugar for the following:
You can see the keys writable, enumerable and configurable here. What do they all mean?
Writable
This determines whether you can change the property.
Consider the following:
Because we set the cat.color property to writable = false, we’ve fixed the pointer the property is pointing to.
Be aware that this won’t throw an error unless you have 'use strict at the top.
That also means that the following will work:
Why did this work? We’ve fixed the pointer for cat.name, but that doesn’t automatically mean we’ve fixed the values within that. If you want the whole object to be readonly:
Enumerable
When set to true, this allows the property to:
show up in for loops
show up in the object keys
be serialised into json
Note: when enumerable is set to false, you can still access the property, but only if you know to look for it directly.
Configurable
When set to false, this stops:
the enumerable property from being changed.
the configurable property from being changed back to true.
any property from being deleted.
However you can still change the writable property to true/false.