The Ultimate Guide to JavaScript Objects with Examples

If you are moving your first steps in learning JavaScript, you must have a good understanding of objects. They are the basis for pretty much everything useful in JavaScript.

Photo by Javier Allegue Barros on Unsplash

Since I’ve started working with JavaScript frameworks, objects have become my best friends and my main goal here is to make objects easier than ever for you.

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 arrayanother 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:

  1. using the literal notation
  2. using the Object() constructor
  3. using Object.create()

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:

  1. the dot notation.property
  2. using square brackets["property"]

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.

Delete property

To remove a property from an object, use the JavaScript delete operator.

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.

Conclusion

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. πŸ˜„


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *