[JavaScript] Objects & Symbols
category: Website | course: Advanced Javascript | difficulty:We’ve already discussed objects in great detail, but not so long ago two new concepts were introduced which I would like to talk about.
Immutable Objects
Sometimes, you want to prevent the user (or yourself) from editing an object once it has been created. You can, to some extent, do this with immutable objects, which has two implementations:
- Frozen Objects: You can’t add/remove properties, nor change any existing properties, unless they are objects.
- Sealed Objects: You can’t add/remove properties, but you can edit existing properties
To freeze an object, use Object.freeze(obj)
. You can check if an object is frozen with Object.isFrozen(obj)
.
To seal an object, use Object.seal(obj)
. You can check if an object is sealed with Object.isSealed(obj)
.
var obj = {a:0, b:1 }; Object.freeze(obj); obj.c = 2; console.log(obj); //Prints {a:0, b:1}
Symbols
A special type of immutable data, is a symbol, which is actually its own data type and part of the primitives. Once you create a symbol, it is unique, even if you create a new one with the same description. Symbols in itself have no function and can’t be altered after creation, but you can use them as a property for an object. Now, because symbols are unique, the only way to access that particular property is if you have a reference to the original symbol. You can’t find the property by means of hasOwnProperty()
or looping through the object. This, of course, is mainly useful for security reasons.
To create a symbol, use Symbol("description")
. The description is optional.
var obj = {}; var sym = Symbol("desc"); var sym2 = Symbol("desc"); obj[sym] = "Yes!"; console.log(obj[sym2]); //Prints undefined console.log(obj[sym]); //Prints "Yes!"
Do not type the keyword new
in front of a symbol declaration. Symbols are not Objects.