In this article, we will be delving into the world of objects in JavaScript. Understanding the concept of objects and how they work is important for writing code in JavaScript. This article is geared towards individuals who have a basic knowledge of JavaScript and are interested in exploring its various data types.
You might want to check out my articles on:
These articles will help you familiarize JavaScript basics.
We will be covering the basics of objects in JavaScript, including their properties, methods, and how they are used to store data in a structured manner. You will learn about object literals, object constructors, and the difference between the two. By the end of this article, you will have a solid understanding of objects in JavaScript and how to work with them in your code.
Definition of Object:
Objects in JavaScript are a combination of key-value sets and are an essential Non-primitive data type in the language. They are employed to store and manage data and can be used to portray real-world items or abstract ideas.
You can know more about Non-primitive datatypes in one of my articles, where I have explained everything about it in detail.
Syntax:
const object_name = {
key_name1 : value1,
key_name2 : value2,
key_name3 : value3,
...
}
It's quite different from the primitive data type, which has no properties or methods (Number, String, Boolean, null, undefined, and symbol).
Objects can have a combination of primitive data types & reference data types.
An object is a reference data type, therefore they are dynamic. When we want an object and create a variable to assign some values to the object, that variable will not store the value directly instead it will point to the location in memory where the object is stored.
To know more about primitive & reference data types, I have a dedicated article on the topic of Primitive data types vs Reference data types
Declaration of an object:
It is a common practice to declare objects with the const
keyword, it will store the object's memory location. But we can add, modify or remove an object’s properties.
Now we see different ways of defining and creating new objects.
1. Using Object Literal:
An object literal is a set of key-value pairs enclosed in curly braces {}
. Each key is followed by a colon and a value, and the key-value pairs are separated by commas. Object literals are a simple and convenient way to create objects in JavaScript. They allow you to define properties and methods clearly and concisely, and they are widely used in the language.
Here is an example of an object literal that defines a car object:
const car = {
// string in object
name: "Z4",
company: "BMW",
// number in object
model: 2023,
// Array in object
color: ['White', 'Black', 'Blue', 'Red', 'Silver'],
// Object in object (nested object)
variants: {
BasicModel: 'sDrive 20i-1998cc',
TopModel: 'M 40i-2998cc'
},
// function in objects
specs: function () {
console.log(`This is ${this.company} ${this.name}, Top variant ${this.variants.TopModel} ${this.model} model in ${this.color[2]}.`);
}
};
In this example, the object car
has all types of data values ( string, number, array, & object) & functions. Every value has there own name, which is known as a key. A key is a string also called a property name (in this case keys are name
, company
, model
, color
, variants
& specs
.)
Functions in an object are referred to as the object's method, which allows the object to do some kind of functioning with the object's data. In the above example, we have defined specs
a function in an object car
, so when we call that function using syntax car.specs()
it will print the sentence as shown in the image below:
We can access, add, modify or delete properties and functions in objects. We will see this in the properties section later on.
The
this
keyword in the function of object, which I will be covering that topic in Methods later on in this article.
2. Using the JavaScript Keyword new
:
We will see this by creating the same object that we created in the above example by using new Object();
Here is an example of an object created using new
the keyword that defines a car object:
// object using new keyword
const car = new Object();
car.name = "Z4";
car.company = "BMW";
car["model"] = 2023;
car["color"] = ['White', 'Black', 'Blue', 'Red', 'Silver'];
It's creating a new empty object and then adds properties using the dot notation or bracket notation. we will discuss this dot & bracket notation later on.
When you will see it in your console, it will show like this:
Just remember, the examples above do the same. But for readability, simplicity and execution speed, use the object literal method.
3. Create an object using Object.create()
:
By this method, we can create a new object from another object using Object.create()
It will inherit the properties from the object, which is defined by its name in parenthesis (in this example Object object1
).
syntax:
object2 = Object.create(object1);
Example:
const object1 = {
rocket: 'mangal',
fuel: 3,
};
const object2 = Object.create(object1) // inherit object1's properties into object2
But if we check in Object object2
browser's console, there will be nothing because inherit properties always store in the object's prototype.
We can see a prototype of the Object object2
to see inherited properties from Object object1
.
You might be wondering "what is a prototype? " and what are the inherited properties? Don't worry I have explained these terms in one of my articles please refer to it.
4. Define a constructor function:
In the object literal method, there is some limitation that they cannot create more than one object. Sometimes we need objects of the same structure or type several times which can achieve with the constructor function. And from this function, we can create objects of the same type over and over again by using new
keywords. We will explore this function in the constructor function topic later on in this article.
Properties of Object:
An object's properties are the key-value pairs that denote the object's state. These can be accessed either by dot notation or bracket notation. For example, if we possess an object called car
and it has a property called name
, we can get to the property either with car.name
or car['name']
. Objects are dynamic so we can access, add, modify, or delete properties and functions in objects during run time.
Accessing Object's Properties:
Syntax:
objectName.keyName // example:- car.name
objectName['keyName'] // example:- car['company']
objectName[expression] //example:- car.company +' '+ car.name +'is nice car';
Example: See below examples in your browser's Console
car.name // Using dot notation:
//OR
car['company'] // Using bracket notation:
Expression:
"This is " + car.company + ' ' + car.name + ' Top variant ' + car.variants.BasicModel + ' ' + car.model + ' in ' + car.color[3]
The output will be like this:
Adding New Properties in Object:
Syntax:
objectName.keyName = value;
Example:
car.fuel = 'Petrol'; // dot notation
// or
car['fuel'] = 'Petrol'; // bracket notation
Now if you see in your browser console, an object car
will show with this new property fuel: 'Petrol'
see in the image below:
Example:
Now if you see in your browser console, an object car
will show with this new method Goodcar: function()
and you can call it by its syntax car.Goodcar()
. See the image below:
Deleting New Properties in Object:
The delete
keyword deletes a property from an object:
Syntax:
delete objectName.keyName;
Example:
delete car.fuel; // it will delete fuel property from object (car).
// OR
delete car['fuel']; // bracket notation
The delete
keyword only works with objects. It's designed to delete object properties, we can't use delete
keyword to delete a variable or function.
Accessing Nested Objects:
const car = {
name: "Z4",
company: "BMW",
model: 2023,
variants: {
BasicModel: 'sDrive 20i-1998cc',
TopModel: 'M 40i-2998cc'
}
};
When we have the object in an object and we can access them using the dot or the bracket notation:
car.variants.BasicModel; // dot-notation & dot-notation.
car.variants['TopModel']; // dot-notation & bracket-notation.
//OR
car['variants']['TopModel']; // bracket-notation & bracket-notation.
Methods of Object:
Methods are functions that are associated with an object. These can be used to do actions or calculations on the object's properties. For instance, a person object may have a method called "sayHello" that returns a greeting inclusive of the person's name. Just remember that methods are functions stored as objects' properties.
Before going into methods let's first see about this
keyword.
What is this
?
You might be wondering what is the role of this
keywords in the object's method. this
is a keyword therefore you can change the value of this
.
Remember the
this
keyword simply refers to its parent object only, suppose you define the same variable outside the object thenthis
keyword will not refer to that variable. Let's understand this with an example:let x = 50; const object = { x: 30, method() {console.log(this.x);} } // Here 'this' will refer to the object's property 'x', not to the variable x that is outside the object.
It's not very useful when you have a single object, but it will be more useful when you have many objects or create objects using the constructor function. Because it will be helpful to use the same method for every object you create.
Take a look at the example below:const car = { name: "Z4", company: "BMW", specs: function () { console.log(`This is ${this.company} ${this.name}.`); } } const bike = { name: "R1", company: "Yamaha", specs: function () { console.log(`This is ${this.company} ${this.name}.`); } }
In this case, we have the same method called
specs
with the same code in both objectscar
&bike
, but we will get different outputs when we call them, See the outputs in the image of the browser's console below:
Accessing Object's Methods:
Syntax:
objectName.methodName()
Example:
car.specs()
Adding Methods in Objects:
It's easy to add a method to an object just like adding a property.
Syntax:
objectName.methodName = function(){
// ....line of codes....
}
Example:
car.Goodcar = function () {
console.log(`${this.company} ${this.name} is a very beautiful car`);
}
Now if you see in your browser console, an object car
will show with this new method Goodcar: function()
and you can call it syntax car.Goodcar()
. See the image below:
Accessors of Object:
Accessors are unique methods that are used to get or set the value of an object's property. These are defined using the "get" and "set" keywords and are usually used to create a layer of abstraction or verification.
JavaScript Accessors (Getters & Setters)
Getters and Setters are introduced by ECMAScript 5 in the year 2009. They allow you to define object accessors.
The get
Keyword (Getter):
This Keyword ties up an object property to a function that will be called when that property is picked up or referenced. It is also used in classes.
Getter functions are immutable, which means we cannot change their values. And we don't need to add parenthesis () while calling getter functions.
Syntax:
get propertyName(){
// Code lines....
}
Example:
In this example, we will use specs
property to get the value, which is inside the curly braces {}
const car = {
name: "Z4",
company: "BMW",
model: 2023,
color: 'Blue',
get specs() {
console.log(`This is ${this.company} ${this.name}, ${this.model} model in ${this.color}.`);
}
}
car.specs // To call the getter function of object using a get keyword.
So if check it In the browser's console, we get the values getter function by just saying car.specs
no need to write parenthesis (like when we call a normal method of object). Checkout the output:
The set
Keyword (Setter):
This Keyword ties up an object property to a function that will be called when there is a need to set that property. It is also used in classes.
Syntax:
set propertyName(parameter){
// Code lines....
}
// parameter can be anything you want to define.
Example:
In this example, we will use carname
property to set the value, which is inside the curly braces {}
const car = {
name: "Z4",
company: "BMW",
model: 2023,
color: 'Blue',
get specs() {
console.log(`This is ${this.company} ${this.name}, ${this.model} model in ${this.color}.`);
},
set carname(name) {
this.name = name;
}
}
car.carname = "X3"; // Giving new value to set it using setter.
Here in the above Example what we did is introduced a new function carname
in our object car
using set
keyword and then we try to set the new value of name
property, which was "Z4"
initially. And When we call the getter function it returns the new value that we have set.
See the console output in the image below:
To Delete the getter and setter:
delete objectName.propertyName;
// Example
delete car.specs; // getter function.
delete car.carname; // setter function.
Function Vs Getter:
Let's the difference between the Function example and the Getter example.
Before going further, if you don't know "What is a function in JavaScript?". You should check out my article on Functions in JavaScript.
Example 1:- Function:
const car = {
specs: functin(){
console.log(`This is ${this.company} ${this.name}, ${this.model} model in ${this.color}.`)
}
}
car.specs()
Example 2:- Getter:
const car = {
get specs(){
console.log(`This is ${this.company} ${this.name}, ${this.model} model in ${this.color}.`)
}
}
car.specs
When it comes to Function, we access a function with parenthesis as in Example1:
car.specs()
.And when it comes to Getter, we access it as a property as in Example2:
car.specs
.
Object.defineProperty():
This method is also used to add Getter and Setters functions in objects. To know about this method here is documentation that you might want to check out: Object.defineProperty() method in JavaScript.
To add Getter and setter functions using Object.defineProperty()
method:
Syntax:
// Adding getter
Object.defineProperty(objectName, "propertyName", {
get: function () { ....Code lines.... }
});
// Adding setter
Object.defineProperty(objectName, "propertyName", {
set: function (parameter) { ....Code lines.... }
});
Example:
const car = {
name: "Z4",
company: "BMW",
model: 2023,
color: 'Blue',
}
Object.defineProperty(car, "specs", {
get: function () { console.log(`This is ${this.company} ${this.name}, ${this.model} model in ${this.color}.`); }
});
Object.defineProperty(car, "carname", {
set: function (name) { this.name = name;}
});
See the console output in the image below:
As you can see it's the same as when we define the getter and setter in the normal way in the object above. But you might be thinking then why do we need to use this method? it only adds extra lines to our code, well here is the answer to your doubt. Using this method to define properties in objects allows us to take control of their behaviour. It can be used to create read-only properties, prevent properties from being enumerated, and more. Don't worry refer to this documentation regarding the Object.defineProperty()
method in JavaScript, which explained everything that you require to learn about this method.
Benefits of Object Accessors:
It makes for simpler syntax since it allows for identical syntax for both methods and properties, which may be desirable. It can help ensure better data quality by securing that properties are set. In addition, it may be used to perform related work behind the scenes.
Constructors of Object:
When only one object is created, using object literals is fine, but if we want to create more than one object, using object literals is frustrating. We have to write out the same code for every object we want to create and every time we want to change some of the object's properties like adding a color
property, we have to remember to update every object. This problem can be resolved by the constructor function:
Before going ahead you need to have basic knowledge of JavaScript functions. For that, you might want to check out my article on Functions in JavaScript.
Constructor function:
Using the constructor function we can make a blueprint (structure or type) of objects we want to create. And objects are created by calling the constructor function using new
keyword. So we could rewrite our previous example from object literal:
Example:
// Constructor function:
function Vehicle(name, company) {
this.name = name;
this.company = company;
this.specs = function () {
console.log(`This is ${this.company} ${this.name}.`);
};
}
For creating objects from the constructor Vehicle
, we need to it using new
keyword:
const car = new Vehicle('Z4', 'BMW');
const bike = new Vehicle('R1', 'Yamaha');
const truck = new Vehicle('T.10', 'Tata');
It will create three objects from the constructor Vehicle
of name car
, bike
& truck
and store their values through the parameters. As you can see created objects in the browser's console in the image below:
We can also call the method specs
that we've defined in the constructor function:
Note:
In the constructor function,
this
keyword is used to substitute the new object. it doesn't have any value.The constructor function name should start with a Capital letter.
Modify a constructor function:
In the constructor function, we cannot add properties and methods after defining the function, like we add new properties and methods in an existing object.
We can only add properties and methods to the object constructor within the constructor function.
Conclusion:
Objects in JavaScript play a vital role in the language and offer a powerful and flexible way to represent complex data structures. Understanding the properties, methods, and prototypes of objects is essential to writing efficient and effective code in JavaScript. We hope this article has provided you with a deeper insight into the world of objects in JavaScript and helped you to better understand the fundamental concepts. As you continue your journey with JavaScript, it's important to keep practising and exploring the various aspects of the language.
If you want to learn advanced topics of objects, you should read my next article on Prototypes & Prototype Chains in JavaScript.
Thank you for reading. Feel free to comment on this, if found it useful.