Howdy folks! Let's continue from the previous posts of the series focused on learning JavaScript. We are learning JavaScript fundamentals from the freeCodeCamp. I am sure, you are enjoying this as well.
This post will cover the basics of Objects in JavaScript. Let's know about them without any delay.
Objects
Objects in JavaScript are used to store data in a structured way. We can see them as an array with the difference being that instead of using indexes to access or modify the data, objects use properties
.
Now, you may ask, what are properties
? These can be referred to as a key among the key-value pairs that exist in an object. It will be more clear with an example.
var cat = {
"name": "Whiskers",
"legs": 4,
"tails": 1,
"enemies": ["Water", "Dogs"]
};
Here cat
is an object. It contains the key-value pairs separated by a colon(:
). The values to the left of the colon are what we call as properties
. And values to the right of the colon are its value.
Notice the semicolon at the end of object definition(just after the closing bracket).
As you may notice, the value for the property enemies
is an array. This implies that values can be anything. It may even be an object itself.
Now, some quirks about properties:
- Although, in the above example, the properties are defined as strings. But it isn't necessary. You may keep an integer value as a property as well.
- If the property is a single word string, you can even emit quotes around it, for e.g.
var someObject = {
user: "Prashant"
}:
Here user
is a valid property. This happens because JavaScript will automatically typecast them into strings.
Accessing object properties
We can access an object property using two ways:
- Using Dot(
.
) notation
When we know the name of the property, we can access the value associated with it using the dot notation. Let's consider the above cat
object
cat.name; // returns "Whiskers"
- Using Bracket(
[]
) notation
Just like arrays, we can access object properties using square brackets, by enclosing the property name. For e.g. the above statement can also be written as
cat["name"]; // returns "Whiskers"
The main use cases for this particular notation are:
- When the property name has spaces in it. As we can't use dot notation in that case.
-
When we want to access the property, which is stored as a value in a variable.
For e.g.var dogs = { Fido: "Mutt", Hunter: "Doberman", Snoopie: "Beagle" }; var myDog = "Hunter"; var myBreed = dogs[myDog]; console.log(myBreed); // "Doberman"
Here, we stored the property
Hunter
as a variable and then accessed it using the variable name instead of the property name directly.
This is also useful when the property name is collected dynamically.
Updating Object properties
We can update object properties, by setting it to something else. Yes, it's as simple as that. We know how to update the variable, just like that.
Let's see a small example, for quick understanding
var cat = {
"name": "Whiskers",
"legs": 4,
"tails": 1,
"enemies": ["Water", "Dogs"]
};
cat.name = "Camper";
cat["name"] = "Camper";
cat.name; // Now it will return "Camper" :)
As you can see, you can set the values by using any of the dot or bracket notations.
Adding properties to an Object
Adding a property to an existing object is exactly similar to how we update an object. We set the property name to value and since the property doesn't exist, JavaScript will create that for us. Isn't that awesome? :)
Let's add a voice property to our cat object
cat.voice = "meww";
Next time, when you'll try to access the voice
property, you'd get meww
in return.
Deleting properties of an Object
We can also delete a property of an object. This can be achieved using the delete
keyword. Let's understand with an example
delete cat.voice;
This would delete the property voice
of cat
object.
Objects find their usage when the data in the form of a dictionary is to be maintained.
Checking object for a property
We might need to know if some property of an object exists or not. This can be easily done with the .hasOwnProperty(propertyName)
method. The method name is itself quite self-described.
We can use this method as
cat.hasOwnProperty("voice"); // returns false as we have deleted it
cat.hasOwnProperty("legs"); // return true
Objects can be used to handle flexible data. An example from freeCodeCamp itself for a complex object can be seen as
var ourMusic = [
{
"artist": "Daft Punk",
"title": "Homework",
"release_year": 1997,
"formats": [
"CD",
"Cassette",
"LP"
],
"gold": true
}
];
Here ourMusic
is an array of objects, currently containing the single object. Further, format
property is also an array, which can be seen as a nested array. This is just one example of how objects can be useful to store a structured but flexible data.
Accessing nested array just like above can be achieved by chaining the array bracket and dot notation. For e.g., if we have to get the 2nd format of the 1st musical album, we'd do something like this
var format = ourMusic[0].formats[1]; // returns "Cassette"
Conclusion
With the end of this short post, we have acquired some knowledge about the Objects in JavaScript. They play an important role in daily JavaScript coding. I am sure, it'll be really helpful to anyone learning JavaScript.
References
Let’s meet next time with another JavaScript post covering some other fundamentals. Till then be curious and keep learning.
Top comments (2)
Nothing about getters and setters?
This post is based on the freeCodeCamp curriculum. The basic JavaScript section involves mainly these topics.
getters
andsetters
would appear in upcoming posts, where we'll explore more about Object-Oriented Programming.Keep an eye on the series, it'll certainly be available in upcoming posts.