Objects are the general building block upon which much of JavaScript is built. They are one of the six primary types in JS: string, boolean, number, null, undefined and object.
There are two types of objects.
- literal form - you can add one or more key/value pairs
var myExample = {
key: value;
};
- constructed form - you must add the properties one by one
var myExample = new Object();
myExample.key = value;
Accessing objects
The contents of an object consist of values stored at specifically locations, called properties.
Consider the next example:
var myExample = {
a:3;
};
myExample.a; //3
myExample["a"]; //3
To access the value at the location a
in myExample
we use either "." or "[]". The ".a" syntax is referred to as "property access" and "["a"]" syntax is usually referred to as "key access". In reality the both access the same location, so both terms can be used interchangeably.
Property descriptor
All properties are described as property descriptor, because an object property is much more than just its value. It includes three other characteristics:
- writable - the ability to change the value of a property.
- configurable - as long as a property is configurable, we can modify its descriptor definition.
- enumerable - controls whether a property will show up in certain object-property enumerations, such as
for..in
loop.
Immutability
Objects can have their mutability controlled to various levels of immutability. All the approaches that are going to be mentioned create a "shallow immutability". This means that they affect only the object and its direct property characteristics.
- Object constant - by combining "writable: false" and "configurable: false", you can create a constant as an object property.
- Prevent extensions - if you want to prevent an object from having new properties, call
Object.preventExtensions()
-
Object.seal()
- it takes an existing object and callsObject.preventExtensions()
on it and marks all its existing properties as "configurable: false". -
Object.freeze()
- it takes an object and callsObject.seal()
on it and marks the existing properties as "writable: false", so that their values can't be changed; this is the highest level of immutability that can be attained.
Top comments (0)