What is an object?
Objects basically are a special kind of variables. They can hold multiple values because an object is made up of an indefinite number of properties.
Each property consists of a pair of key and value.
The key is the name of the property.
The value could be a string, a number, a boolean, an array, another object (called nested object) or a function.
If the value of a key contains a function declaration, the property is called method.
Create an object
According to MDN, there are 3 ways to initialize an object:
My go-to method is the literal notation because it’s a short form of initializing an object that consist in enclosing in curly braces a comma-delimited list of zero or more properties.
Add properties to an object
Properties can be declared with two possible notations:
- the dot notation,
- using square brackets,
Access property value
To access object properties both the dot notation and the square brackets can be used.
If the property is a method, its value can be access only using the dot notation with the parenthesis.
If you need to make sure if an object has a property or not, use the
hasOwnProperty() method to check if it exists.
Update property value
To update the value of a specific property of an object, access the property first then just use
= to assign it the new value.
Duplicate an object
Many times I face the need to manipulate an object keeping intact the original.
To have an independent copy of an object, the only way to achieve the goal is to use the
... spread operator: only reassigning the object to another variable won’t do the trick, it’s only going to make the object accessible via two different variables.
I hope this article has helped you become more familiar with objects.
Objects will be your best friends, believe me. 😉
If you have any doubts or questions, feel free to leave a comment. 😄