Objects cheatsheet
Basic usage
Objects are used to store keyed collections of various data and more complex entities.
const app = {
name: "todo",
version: 1.2,
};
alert(app.name); // todo
alert(app.version); // 1.2
app.version = 1.3; // update value
app.license = "MIT"; // add new property
delete app.version; // delete propertyMultiword property name
const game = {
name: "sudoku",
"is free": true,
};
alert(game["is free"]); // true
const isFree = "is free";
alert(game[isFree]); // trueComputed property
Property value shorthand
References and copying
Copying objects When copied, the new object will be a reference to the original object, unlike regular variables, which create independent entities when copied
Object comparison The comparison operators
==and===work the same for objects
Cloning objects
Object.assign(target, ...sources)- copies all enumerable own properties from one or more source objects to a target object.
Iterating objects
Loop for...in
Object.keys(object) Returns an array of keys of the passed object
Object.values(object) Returns an array of values of the passed object
Object.entries(object) Returns an array of the [key, value] pairs of the passed object
Object methods & this
Object methods In addition to values, objects can have methods that perform various actions
this
thisallows to refer to variables and methods that are stored in the same object
this is simply a reference to the object in the context of which it was called
Constructors
Constructor functions Constructor functions are used to easily create objects. They are normal functions, but developers have agreed that such functions are capitalised and called with
newoperator.
Methods in constructors
Property existance
Checking property existence
Optional chaining Is a safe way to access nested object properties, even if an intermediate property doesn’t exist
Flags & descriptors
Object properties can store a special configuration flags in addition to the value.\
writable – if true, the value can be changed, otherwise it’s read-only.
enumerable – if true, then listed in loops, otherwise not listed.
configurable – if true, the property can be deleted and these attributes can be modified, otherwise not.
All flags default to true
Object.getOwnPropertyDescriptor(obj, property) Allows to query the full information about a property
Object.defineProperty(obj, property, descriptor) Change the flags of the specified property
Object.defineProperties(obj, {prop: descr, ...}) Allows to define many properties at once
Object.getOwnPropertyDescriptors(obj) Get all property descriptors at once
Getters & setters
Getters and setters called as accessor properties. They are essentially functions that execute on getting and setting a value, but look like regular properties to an external code.
Usage The
getkeyword is used to create the getter, for the setter -set
Accessor descriptors For accessor properties, there is no
valueorwritable, but instead there aregetandsetfunctions
Last updated