Objects: Where JavaScript Comes Alive!
What? You find the heading exaggerated? But trust me. Almost everything in javascript can be traced back to objects. As such it becomes really important to be able to understand what objects are in javascript, their properties, how they behave, what can we do with them and how can we use them practically.
So what is an object in JavaScript?
Well simply speaking its a key value pair. That we all must have already read somewhere. What else? I want you to think - have objects really been like this in other languages? If you come from a c++ or java background you might remember defining a class and then instantiating an object of that class and calling it an object. In Javascript too one can do this but this was a functionality added later. YES! This means that objects are more core to JavaScript than classes themselves. In fact classes are just syntax sugar for already existing functionality in javascript. Which means that key-value pair style is an existing form of a data structure that can be directly used. This freedom opens up many powerful ways of utilizing objects in JavaScript.
In JavaScript objects are usually used to store a group of variables that have a common association with something. For example if we say want to describe a person we would like to group together some of their properties - like name, age , gender, weight , height etc. Now despite all of them being variables of different data types , we can group them together in a meaningful way to get something useful.
const person ={
name:"Tanjiro",
age:16,
gender:'male'
weight:50,
height:160,
}
As we can see we have managed to describe a person's different attributes in a single variable. Also we can easily nest objects inside objects. Like:
const person ={
name:"Tanjiro",
age:16,
gender:'male',
physique: {
weight:50,
height:160,
},
}
They are dynamically allocated in the memory and the reference is what is stored in the variables.
Object Construction
Now that we need to work with objects we need to learn how to create them first. There are many ways in which you can end up with objects in your hands from some function's return value to an API response. But at its core the birth of object happens mostly by 3 main ways.
Literal Allocation
Our first method is to take a variable and directly assign object into it. Just like this:
const person ={
name:"Tanjiro",
age:16,
gender:'male',
physique: {
weight:50,
height:160,
},
}
Okay... so that's it? Yes. At least for what we see. To actually understand what happened - internally the system did :
const person = new Object(
{
name:"Tanjiro",
age:16,
gender:'male',
physique: {
weight:50,
height:160,
},
};
)
A new object was created. Memory was allocated in the heap - the object was stored there and a reference of it was stored in the variable. Not only that, an external property decider called a prototype is attached in the object. For every object this prototype defines what extra properties will it inherit from some other object. The prototype is stored in the object and is not accessible as a property. It stores a reference to another object which defines those extra properties . For this kind of definition the prototype of this object is : Object.prototype. The default prototype of every object .
Using the new Keyword
We can use a constructor function to predefine the properties of an object. This is same as using classes but JavaScript syntax is kind of different, Classes are just syntax sugars. Their role is fulfilled by some special functions and even then objects can be modified to add or remove some property. This is an advantage. Not only can we define properties based on a template we can also have a modified prototype which will be the same as that function's prototypes . And YES- functions are also objects.
Here is how we use it:
function objCreator(name,age)
{
this.name = name;
this.age = age;
return this;
}
const person = new objCreator('Tanjiro',10);
Now the new keyword actually has some more tasks which we will discuss in some other blog. But the same code can be written in the form of classes which will be discussed in detail in another article in this same blog.
Using the Prototype-based allocation
To use the prototype based allocation is to have even more control over the creation of the object. Here one can explicitly set the prototype of their object during creation. To use it we do:
const HumanPrototype = {
type:'human',
desire: function eatfood() { console.log("I eat food");}
}
const person = Object.create(HumanPrototype);
Here a new person will be created with the prototype as HumanPrototype object. This allows us to construct an object with more personalization and it doesn't even run any constructor.
Object Usage
Now that we have created an object we need to learn to use it. We basically have a key value store. What can we want? Accessing the properties. Add or delete key-value pairs. Modify a value. See all keys or values. Loop over the object. All of such functionalities are provided by javascript.
Object Access
Object access is pretty simple in javascript. We have two main methods.
- objectName.keyname :
This will directly give us the value associated with that key name. For example:
const personName = person.name;
console.log(personName);
// Directly prints Tanjiro
- Square bracket Notation :
This is a very powerful approach. Even tho by definition it just allows us to access values by using keys as strings like:
const personName = person['name'];
console.log(personName);
// Directly prints Tanjiro again
But here we get the power to store our keys in a variable as strings and use them later. We can extract keys, use them dynamically or not even know what a key is at a given abstraction level to be able to use that key. We can do:
const key = 'name';
const personName = person[key];
console.log(personName);
// Directly prints Tanjiro again
This is completely valid and extremely useful.
Also before accessing the properties we might need to check if they actually exist.
And NO! Just doing person[name] or person.name doesn't work because the value could be undefined. The 'in' keyword is used to check for the existence of a key - like:
const keyexists = 'name' in person;
But this is dangerous as it might check the properties of prototype and return true based on that.
We can also use person.hasOwnProperty('name') - but the most apt method will be to use -
Object.hasOwn(person,'name');
Addition, Deletion and Update of Properties
The simplest way to add or update a property is to specify them by the dot or square bracket access. For example:
person.age = 30;
//or
person['age'] = 25;
//Updates properties if already exist.
person.city = 'Agra';
person['location'] = 'Nagpur';
//Since these properties did not exist they were added to the object
Similarly deletion is just writing the delete keyword before the property access. For example:
delete person.city;
//or
delete person['location'];
This deletes that property. Also it is important to note that the delete property only influences object's own property and not if the property was present in the object's prototype.
There are some other ways to create a property in an object - like creating a new object with the same properties using a spread operator , adding that property and assigning them back to the object but that is equivalent of holding one's ear from under the leg.
Looping over Objects
Now that we have an object we can see it is just a set of key value pairs. And that means it is iterable . As such JavaScript is obliged to provide us with features to iterate and it does comply.
We can use the popular for in loop:
for(const key in person)
{
console.log(`\({key} : \){value}`);
}
But this would have the same problem as in based access - it will take in inherited properties also. To avoid this - actually we don't have to do anything. The developers have already set its enumerable property as false. So it doesn't appear so feel free to use it. There are other ways to use it like extracting keys or entries but that would be more fun when you do it yourself after learning array methods.
With that we can conclude our basics of objects. Yes these are just the basics.Objects are the heart of javascript for a reason. There is nigh infinite depth to dive into and we are definitely not stopping here.