Unlocking the Secrets of JavaScript Objects: A Comprehensive Guide


What is Object?
In JavaScript, an object is a collection of key-value pairs, where each key-value pair is referred to as a property.
The keys of objects can be strings or symbols, and the values can be strings, numbers, functions, or even other objects.
Let's take an example to understand this concept better. Consider this Car object:
The properties of this car are
Name : Nissan GTR R32
Production company : Nissan
Nickname : Godzilla
Engine : Twin turbocharged 2.6L inline six
Power Produce : 276HP
These are some of the properties of object Car.
How to create object?
There are three methods to create an object. The first is using object literals, the second is creating a constructor function and then initializing it, and the third is using the Object.create()
method.
These methods do the same thing and produce the same result.
Using Object literals
This method is the most common for creating objects. The syntax is
let car = {}
This is how to declare the object. To create an object with properties, we use key-value pairs.
let car = {
// propertyKey : propertyValue
name: "Nissan GTR R32",
nickname: "Godzilla", // or else we can also write like this -> "nickname": "Godzilla"
introduction_year: 1989
}
In this, we can write like "Property Key": "Property value," but we write like Property Key: "Property value" because JavaScript automatically converts the name into a string without needing "".
The properties are separated by comma (,
).
Using Constructor functions
You can create an object using a constructor function in two steps:
Define the object type by writing a constructor function
create an instance of the object using the
new
keyword
Syntax :
function Car(name, engine) {
this.name = name,
this.engine = engine
}
const car = new Car("Nissan GTR R32", "Twin turbocharged 2.6L Inline Six")
In this code, we create a function Car that takes a name string and an engine string and stores the values in name and engine, respectively, using the this keyword. car is the object of Car.
Using Object.create()
Objects can also be created using the Object.create()
method. This method can be very useful because it allows you to choose the prototype object for the object you want to create without having to define a constructor function.
Syntax :
const Animal = {
type: "Invertebrates", // Default value of properties
displayType() {
// Method which will display type of Animal
console.log(this.type);
},
};
// Create new animal type called animal1
const animal1 = Object.create(Animal);
animal1.displayType(); // Logs: Invertebrates
In this code, we created an object Animal and then created an object animal1 using Object.create(Animal)
.
Properties of Object
JavaScript objects have properties associated with them. Object properties are the same as variables, but they are linked to objects and not to scopes. They define the characteristics of the object.
Let's take an example and understand the properties of an object.
let Person = {
name: "Rahul",
age: 20,
phone_no: 9999900000,
fullName: { // this is how you create a property with funtion as a value
firstName: "Rahul",
lastName: "Singh"
}
}
This will help you visualize the object.
+----------------+
| Person |
+----------------+
|
---------------------------------------
| | | |
+-------+ +------+ +-------------+ +------------+
| name | | age | | phone_no | | fullName |
| "Rahul"| | 20 | | 9999900000 | +------------+
+-------+ +------+ +-------------+ |
-----------
| |
+----------+ +---------+
|firstName | |lastName |
| "Rahul" | | "Singh" |
+----------+ +---------+
Accessing the property values
There are two notations to access the property of object.
dot notation
array / bracket notation
dot notation
Syntax :
objectName.propertyName
For example, let print the name, age and phone number of Person object
console.log(Person.name) // output : Rahul
console.log(Person.age) // output : 20
console.log(Person.phone_no) // output : 9999900000
console.log(Person.fullName.lastName) // output : Singh
array/bracket notation
Syntax :
objectName["propertyName"]
For example, print the name, age, and phone number of Person.
console.log(Person["name"]) // output : Rahul
console.log(Person["age"]) // output : 20
console.log(Person["phone_no"]) // output : 9999900000
Both notations print the same thing. However, if we use a symbol or a string (datatype) as a property key, we must use array/bracket notation because dot notation cannot print the value and will give an error. Let's take an example,
let Person = {
name: "Rahul",
age: 20,
phone_no: 9999900000,
"": "This is empty string",
[symbol]: "this is symbol datatype"
}
console.log(Person."") // error
console.log(Person.symbol) // undefined
console.log(Person[""]) // output : This is empty string
console.log(Person["symbol"]) // output : this is symbol datatype
These are two notations used to access the properties of objects.
Modifying the value of a property
We can modify the property value of the properties present in the object using the =
operator. For example,
let Person = {
name: "Rahul",
age: 20
}
Person.age = 50
console.log(Person.age) // output : 50
In this code, we changed the value of age, which was previously 20 and is now 50.
Adding a new property to an object
You can add new properties to an object without creating the property inside the object. For example,
let desserts = {}
desserts.variety = "50"
console.log(desserts.varirty) // output : 50
In this code, we create an object and then add a property to the desserts
object.
Deleting a property of an object
We can delete the properties of objects using the delete
keyword. Syntax :
delete object_name.property_name
For example, take a object Person and delete the phone number of Person
let Person = {
name: "Rahul",
age: 20,
phone_no: 9999900000
}
delete Person.phone_no
console.log(Person.phone_no) // output : undefined
In this code, we deleted the phone_no
property of Person
.
Checking if a property exists
To check if a property exist in object, we can use two keywords
in
keywordhasOwnProperty
keyword
in
keyword
If a property exists in an object, it will return true; otherwise, it will return false.
Syntax :
property_name in object_name
For example, take an object and check if a property exists.
let man = {
name: "Himanshu",
age: 20
}
console.log("name" in man) // output : true
console.log("phone_no" in man) // output : false
In this code, we check if name
exists in man
, which returns true, meaning it exists, and we checked if phone_no
exists in man
, and it returns false.
hasOwnProperty
keyword
It also return true if property exist in object or else return false.
Syntax :
object_name.hasOwnProperty(property_name)
For example,
let man = {
name: "Himanshu",
age: 20
}
console.log(man.hasOwnProperty("name")) // output : true
console.log(man.hasOwnProperty("phone_no")) // output : false
In this code, we check if name
exists in man
, which returns true, meaning it exists, and we checked if phone_no
exists in man
, and it returns false.
Merging Objects
We can merge two or more objects together using the Object.assign()
method. This method copies all the properties of source objects to the target object. It returns the target object.
Syntax
let obj = Object.assign(target_obj, source_obj1, source_obj2, ...)
For example, take two objects and merge them
let obj1 = {
1 : "a",
2 : "b"
}
let obj2 = {
3 : "c",
4 : "d"
}
let new_obj = Object.assign(obj1, obj2)
In this code, all the properties of obj2
will be copied into obj1
. But if we want to copy the properties of obj1
and obj2
into another empty object, we can do that.
let new_obj = Object.assign({}, obj1, obj2)
There is another method by which we can merge two or more objects.
Syntax :
let obj = {...obj1, ...obj2}
That’s it. This method is easy and mostly used because we don’t have to write extra parentheses. For example,
let obj1 = {
1 : "a",
2 : "b"
}
let obj2 = {
3 : "c",
4 : "d"
}
let new_obj = {...obj1, ...obj2}
This will print the same as Object.assign()
method will print.
Conclusion
In conclusion, understanding JavaScript objects is fundamental to mastering the language and enhancing your programming skills. Objects in JavaScript serve as versatile structures that allow developers to store, manipulate, and manage data efficiently. By exploring various methods of object creation, such as object literals, constructor functions, and the Object.create()
method, you can choose the most suitable approach for your needs. Additionally, knowing how to access, modify, add, and delete object properties, as well as merge objects, empowers you to build more dynamic and robust applications. As you continue to work with JavaScript, leveraging the power of objects will undoubtedly lead to more efficient and effective code.
Reference Links :
MDN Docs : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_objects
JavaScript Tutorial : https://www.javascripttutorial.net/javascript-objects/
chai aur code (part-1) : https://www.youtube.com/watch?v=vVYOHmqQDCU
chai aur code (part-2) : https://www.youtube.com/watch?v=4lb2pXWWXJI
Subscribe to my newsletter
Read articles from himanshu directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
