Mastering JavaScript Objects: A Comprehensive Guide for Developers
Unveiling the Power of JavaScript Objects
Did you know that in JavaScript, everything is an object or can be converted into one using the new
keyword? Objects are fundamental building blocks of modern JavaScript, and understanding them is essential for any developer.
Hello and welcome to the new blog where we explore the fascinating world of JavaScript Object. Let's explore the many facets of JavaScript objects. From declaration to manipulation, we'll uncover the secrets of creating, accessing, modifying, adding, and removing object properties. Prepare yourself for a thrilling journey!
Understanding JavaScript Object
In JavaScript, everything is an object or can be converted into one using the new
keyword. So what exactly is an Object?
In JavaScript, an object is a container that holds various properties (which are mutable) and methods (functions) as a single unit. In JavaScript, an object is an unordered collection of key-value pairs. Each key-value pair is called a property.
Let's understand the property and methods,
Properties: Properties are the characteristics of an object. They are defined using a key-value pair. The key is an identifier and it can be either a string
, number
or symbol
and value can be any data type (including functions and other objects).
Method: The method is essentially a function, that is stored as properties in the Object. These methods can be executed by calling through an object they belong to.
As mentioned earlier, in JavaScript, everything is an object or can be converted into one using the new
keyword. Let's explore what can be made into objects.
Numbers can be made objects using the new keyword
Boolean can be made an object using the new keyword
Strings can be made objects using the new keyword
An array is an object
A function is an object
A date is an object
Regex (Regular Expression) is an object
Maths is an object
Objects are always objects
Object Structure
Creating Objects
There are five ways to create Objects in JavaScript
Object Literals
Constructor function
using new keyword
ES6 classes
Factory Functions
Object Literals
The most common and straightforward way to create an object in JavaScript is by using object literals. It uses curly braces {}
to define an object and its properties
const jsUser = {
name: "Subramanya",
age: 18,
location: "Bengaluru",
email: "Subramanya@google.com",
isLoggedIn: false,
lastLoginDays: ["Monday", "Saturday"],
userDetails: function () {
console.log(
`user name is ${this.name} and work location is ${this.location}`
);
},
};
JsUser.userDetails();
console.log(jsUser)
/*
OUTPUT
user name is Subramanya and work location is Bengaluru
{
name: 'Subramanya',
age: 18,
location: 'Bengaluru',
email: 'Subramanya@google.com',
isLoggedIn: false,
lastLoginDays: [ 'Monday', 'Saturday' ],
userDetails: [Function: userDetails]
}
*/
In the above example, we have created an object named jsUser
with properties and a method.
You may have seen the this
keyword in the object. Let's understand its usage before moving further.
What is this
referred to in an Object?
this
is a special keyword that refers to the current execution context or scope. When it comes to object this
refers to the object itself. Let's understand by taking an example.
let electricBike = {
makeer: "Ather",
model: "Ather 450X",
year: 2023,
price: "1.5 lacs",
getDetails: function(){
console.log(`Electric scooter from ${electricBike.makeer}, model name is ${this.model}, year of release is ${this.year}, and the price is ${this.price}`)
}
}
electricBike.getDetails();
/*
OUTPUT
Electric scooter from Ather, model name is Ather 450X, year of release is 2023, and the price is 1.5 lacs
*/
In the example, you can see that I have used this
as well as the object name. You can see the output is the same in both cases.
However, the value of this
is determined by how the function is called, not by where it is defined. let's take the same example and try to understand.
let electricBike = {
makeer: "Ather",
model: "Ather 450X",
year: 2023,
price: "1.5 lacs",
getDetails: function(){
console.log(`Electric scooter from ${electricBike.makeer}, model name is ${this.model}, year of release is ${this.year}, and the price is ${this.price}`)
}
}
let electricBikeDetails = electricBike.getDetails;
electricBikeDetails();
/*
OUTPUT
Electric scooter from Ather, model name is undefined, year of release is undefined, and the price is undefined
*/
when electricBikeDetails()
is called, it is not called a method of electricBike
object. so this
does not refer to the electricBike
object. Instead, this
refers to the global object, and the properties of the electricBike
object is not accessible.
Wherever I used electricBike
object it gives you the correct value.
Constructor function
A function with the blueprint is created. Whenever you want to create an object use new
keyword along with properties to create an object.
function Laptop(brand, processor, ram, gpu) {
this.brand = brand;
this.processor = processor;
this.ram = ram;
this.gpu = gpu;
}
// here brand, ram, cpu are the keys
const laptop1 = new Laptop("Lenovo", "AMD", 24, "1024mb");
const laptop2 = new Laptop("Dell", "Intel", 16, "1024mb");
console.log(laptop1);
console.log(laptop2);
/*
OUTPUT
Laptop { brand: 'Lenovo', processor: 'AMD', ram: 24, gpu: '1024mb' }
Laptop { brand: 'Dell', processor: 'Intel', ram: 16, gpu: '1024mb' }
*/
In the above example, Person
is a blueprint and using the blueprint you can create many objects.
Use the prototype
property to add the methods to an object and this method is shared by all the objects created by the constructor function.
function Person(firstname, lastname, age) {
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
}
Person.prototype.fullName = function() {
return "My name is " + this.firstname + " " + this.lastname;
}
let person1 = new Person("K", "Subramanyeshwara", 25);
console.log(person1.fullName());
/*
OUTPUT
My name is K Subramanyeshwara
*/
using new
keyword
This method is similar to other class-based languages, ex Java. In this, the object is created using the ‘new’ keyword.
Object()
is a built-in constructor function that is used to create new objects. When called with the new
keyword, the Object()
constructor creates a new object.
let person = new Object();
person.name = "K Subramanyeshwara";
person.age = 26;
person.getDetails = function(){
return `${this.name} is ${this.age} years old`;
};
console.log(person.getDetails());
/*
OUTPUT
K Subramanyeshwara is 26 years old
*/
In the above example, person
object is created. Properties are added later. There are two ways we can add or update the value, which you will learn about in a moment.
ES6 Classes
ES6 supports class concepts like any other object-oriented language, providing a structured way to create objects and making object creation and inheritance more intuitive.
class Person {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
greet() {
return `Hello, I'm ${this.firstName} ${this.lastName} and my age is ${this.age}`;
}
}
const person = new Person('K', 'Subramanyeshwara', 26);
console.log(person.greet());
/*
OUTPUT
Hello, I'm K Subramanyeshwara and my age is 26
*/
Factory functions
Factory functions are a design pattern used to create objects without using the new
keyword or a constructor function. Instead, they return an object directly.
function createCar(maker, model, year, price){
return{
maker,
model,
year,
price,
carBrand(){
return `My car maker is ${this.maker}, model is ${this.model}, manufactured year is ${this.year} and the price is ${this.price}`
}
}
}
let myCar = createCar("Tata", "safari", 2024, 1900000);
console.log(myCar)
console.log(myCar.carBrand())
/*
OUTPUT
{
maker: 'Tata',
model: 'safari',
year: 2024,
price: 1900000,
carBrand: [Function: carBrand]
}
My car maker is Tata, model is safari, manufactured year is 2024 and the price is 1900000
*/
In this example, the createCar()
function is a factory function that takes three arguments (make
, model
, year
, and price
)and returns an object with properties and methods based on those arguments.
Accessing, Updating and Adding new properties of Object
Using the dot operator.
Using the bracket operator.
Accessing the properties of Object
dot .
operator
Using dot operator
you can access the properties of the object by writing the object’s name, a dot (.
), and the property name. The dot operator is most commonly used to access the properties of an object.
const myCar = {
make: "Ford",
model: "Mustang",
year: 1969,
};
console.log(myCar.make);
console.log(myCar.model);
/*
OUTPUT
Ford
Mustang
*/
bracket [ ]
operator
Another way to access the properties of an object is bracket operator
. It is useful when you are not sure about the properties name whether it contains white space or not. It allows you to use dynamic property names.
let Laptop = {
"brand name": "Samsung",
"processor": "Snapdragon",
"RAM": 24,
};
Laptop.gpu = "1024mb";
console.log(Laptop);
console.log(Laptop["brand name"]);
console.log(Laptop["gpu"]);
console.log(Laptop["RAM"]);
/*
OUTPUT
{
'brand name': 'Samsung',
processor: 'Snapdragon',
RAM: 24,
gpu: '1024mb'
}
Samsung
1024mb
24
*/
In the above example, you have seen adding a property to an object. We will dive deeper in a moment.
Updating an existing properties of the Object
Updating the property can be done using both dot
and bracket
notation.
const Laptop = {
brand: "Samsung",
"processor": "Snapdragon",
"RAM": 24,
gpu: "1024mb",
};
console.log(Laptop);
//dot noatation
Laptop.gpu = "2048mb";
console.log(Laptop);
//bracket notation
Laptop["processor"] = "AMD";
console.log(Laptop);
/*
OUTPUT
{ brand: 'Samsung', processor: 'Snapdragon', RAM: 24, gpu: '1024mb' }
{ brand: 'Samsung', processor: 'Snapdragon', RAM: 24, gpu: '2048mb' }
{ brand: 'Samsung', processor: 'AMD', RAM: 24, gpu: '2048mb' }
*/
In the above example, you can see that the objects are printed three times. We updated the properties using both dot and bracket notations.
Handling the non-existing property
Retrieving the property that does not exist inside the object will return undefined.
let person = {
first_name: "K Subramanyeshwara"
};
console.log(person.first_name);
console.log(person.last_name);
/*
OUTPUT
K Subramanyeshwara
undefined
*/
Adding new properties to an Object
Adding the property can also be done using both dot
and bracket
notation.
const Person = {
firstName: "K",
lastName: "Subramanyeshwara",
age: 26,
location: "Bengaluru",
email: "k@remote.com"
}
console.log(Person);
//dot notation
Person.socialMediaPresence = true;
console.log(Person);
//bracket notation
Person["married"] = false;
console.log(Person);
/*
OUTPUT
{
firstName: 'K',
lastName: 'Subramanyeshwara',
age: 26,
location: 'Bengaluru',
email: 'k@remote.com'
}
{
firstName: 'K',
lastName: 'Subramanyeshwara',
age: 26,
location: 'Bengaluru',
email: 'k@remote.com',
socialMediaPresence: true
}
{
firstName: 'K',
lastName: 'Subramanyeshwara',
age: 26,
location: 'Bengaluru',
email: 'k@remote.com',
socialMediaPresence: true,
married: false
}
*/
In the above example, you can see that the objects are printed three times. We added the new properties using both dot and bracket notations.
Deleting properties from an Object
We can delete the property using delete
keyword. If the property is not present then it will simply ignore it. To delete use delete
keyword followed by the object.key
.
const Car = {
name: "Ford",
color: "Red",
price: "$100000",
topSpeed: "220kph"
}
console.log(Car);
delete Car.price;
console.log(Car);
/*
OUTPUT
{ name: 'Ford', color: 'Red', price: '$100000', topSpeed: '220kph' }
{ name: 'Ford', color: 'Red', topSpeed: '220kph' }
*/
In the above example, we have deleted price
property.
Conclusion
Understanding JavaScript objects is fundamental for any developer looking to build robust and efficient applications. This guide has covered the essential concepts of creating, accessing, updating, and deleting object properties.
By exploring various object creation methods and understanding the this
keyword, you can write more predictable and maintainable code.
Continued practice with these concepts will deepen your knowledge and enhance your coding abilities.
Thank you for taking the time to read this article 😊. I hope the article provided you with valuable insights. I would highly appreciate it if you took a moment to like 👍, share your thoughts or feedback comment ✍️, and share 🔁 it.
You can also follow me for more content on CSS, Javascript, React, Git and other web Development topics.
Happy Learning...! ✌️✌️✌️
For Paid collaboration, please mail me at: subramanyeshwarak@gmail.com
If you liked my content, Connect with me on