Objects are the foundation of JavaScript. Everything except primitive data-types(null,undefined,numbers etc.) in JavaScript is an object. So having a strong clench on this concept is very necessary.
JavaScript objects include arrays, functions, constructors, and objects themselves.
In this article, we are going to learn about objects.
This Blog post will cover
- What are objects?
- Properties of objects
- Creation
- Retrieving
- Existence
- Updation
- Deletion
- Iteration
- Comparison
Let's get started
What are Objects?
An object is a standalone entity with properties and values. The value of the property could de number, string, boolean, functions, arrays, and even another object.
According to Mozilla developer's guide "An object is a collection of properties, and a property is an association between a name (or key) and a value.
" In simple terms, objects consist of some key-value pairs called Properties. These properties define objects' behavior and attributes.
In the above example, the Student object has four properties describing it - ID, NAME, AGE, COURSES.
Properties of objects
In this article, we are going to play with objects by performing some operations on them:-
- Creation- Creating an object
- Retrieving- Accessing the Properties of an Object
- Existence- Check whether the particular property exists or not
- Updation- Updating the value of existing property
- Deletion- Deleting the existing property
- Iteration- Looping over an object's properties
- Comparison- Comparing the two objects
Creation
In JS, there are many ways to create objects. Let us look at each of them with examples:-
1.) Using "literal" notation:-
This is the simplest way of creating an object. Here the objects are created with curly brackets. An object is represented as -
const user={ }; //creating an empty object
Empty objects are objects with no properties. You can also specify the properties while creating an object.
const student = {
ID: 5001,
'NAME': 'Neha', // Using string quotes
AGE: 20,
isHosteler: true,
COURSES: ['JAVA', 'ReactJS', 'MYSQL'], //array
parentDetails:{ //nested object
fatherName:'G.K.SONI',
}
message: function(){ //function
return `Hi ${this.NAME}, Welcome to Chitkara University!!!`
};
In objects, the property names(key) are treated as strings and values can be of any type either primitive or non-primitive. When we have a function as a value to the key then this function is called methods.
2.) Using new keyword
Using this method you can first create an object using the new
keyword and then add the properties to it later.
var user=new Object();
user.name="aditya",
user.age=21
4.) Using Constructor
A constructor is a special method that is automatically called when an object is created. We can optionally pass parameters while the creation of an object using a new keyword. This method of creating an object is recommended in real-life projects because you can create as many objects as you would like by using the new keyword. Also if you need to edit or add a property, it's very easy to do it.
const Books = function(title, author, authNationality) {
this.title = title;
this.author = author;
this.authNationality = authNationality;
this.getDetails = function() {
console.log(`${this.title}, by ${this.author}(${this.authNationality});
}
}
const book1 = new Movie('The God of Small Things', 'Arundhati Roy', 'Indian');
const book2 = new Movie('The Bell Jar', 'Sylvia Plath', 'American');
console.log(book1.getDetails());
console.log(book2.getDetails());
Retrieving
The properties assigned to object can be retrieved or accessed by using two ways:-
1.) Dot Notation
Here, the object name and property name are separated by the .
(dot) operator. If the property exists we get its value. If the property doesn't exist we get undefined
.
Example:-
<html>
<body>
<script>
const book = {
title : 'The God of Small Things',
author : 'Arundhati Roy',
authNationality: 'Indian'
}
document.write(book.title+"<br/>");
document.write(book.year);
</script>
</body>
</html>
Using dot notation you can't use the property names that are special characters, numbers, or strings that contain spaces, these will throw a syntax error.
Example
obj.10='ten';
obj.first name='neha';
obj.first-name='neha;
Output
2.) Bracket Notation
We can also access the object by using the square brackets [].
<script>
const book = {
title : 'The God of Small Things',
author : 'Arundhati Roy',
authNationality: 'Indian'
}
console.log(book['title']+"<br/>");
</script>
Bracket notation is more expressive than dot notation because it allows a variable to specify all or part of the property name. Bracket notation also allows property names to contain characters that are forbidden in dot notation.
Example
obj[10]='ten';
obj[first name]='neha';
obj[first-name]='neha;
This is valid!!!
Existence
Sometimes we only want to know whether the particular property exists in an object or not and JavaScript provides you with two common ways to check this:-
1.) hasOwnProperty() method
JavaScript object has a special method obj.hasOwnProperty('propName')
that returns a boolean value indicating whether the propName
exists or not.
Example
<script>
const user = {
name: 'neha'
};
user.hasOwnProperty('name'); // true
hero.hasOwnProperty('age'); // false
</script>
2.) in operator
The in
operator also returns true if propName
exists in an object.
Example
Example
<script>
const user = {
name: 'neha'
};
'name' in user; /* true */
'age' in user; /* false */
</script>
Updation
Updating an object property is very simple. It's just like addition. We can update the value of the property just by reassigning the value to the same key. We can use dot-notation or bracket-notation for this.
Example:-
<script>
const user={
firstName:'neha',
lastName:'sni',
nationality:'American'
}
user.nationality='Indian'; //using dot operation
user['lastName']='soni'; //using bracket notation
</script>
Deletion
Deletion is performed using the delete
operator. The delete operator deletes both the property and the value of the property. Again, we can use dot-notation and bracket-notation for the deletion. The delete
operator returns true if the property was successfully deleted.
<script>
const user={
firstName:'neha',
lastName:'soni',
nationality:'Indian'
}
delete user.nationality='Indian'; /* returns true */
delete user['lastName']='soni'; /* return true */
delete user.age; /* returns false because prop. doesn't exists */
Iteration
An object is a standalone entity with properties and values. Unlike arrays, you can’t simply iterate an object. Here are a few ways to iterate through JS objects to get their keys and values:-
1.) Object.entries()
Object.entries() method returns a multi-dimensional array which contains an array of key-value pair of the object's properties.
Example
<script>
const user = {
name: 'neha',
age: 20,
courses: ['java', 'mysql']
}
const kp = Object.entries(animal)
/* output
[
[ 'name', 'neha' ],
[ 'age', 20 ],
[ 'courses', ['java', 'mysql'] ]
]
*/
</script>
2.) Object.keys()
This method returns the keys of an object in an array and we can now iterate on this returned array and reference the property value with the key.
Here’s an example:-
<script>
const user = {
name: 'neha',
age: 20,
courses: ['java', 'mysql']
}
const allProperties = Object.keys(user);
/*
output=> [ 'name', 'age', 'courses']
*/
for (const property of allProperties) {
const value = obj[property];
console.log(property, value);
}
3.) Object.values
This method is like object.keys
but it returns the value of the properties in an array.
Example
<script>
const user = {
name: 'neha',
age: 20,
courses: ['java', 'mysql']
}
const allProperties = Object.keys(user);
/*
output=> [ 'neha', 20, ['java', 'mysql'] ]
*/
4.) for-in loops
The for-in
loop is used to iterate through an object. You get the properties one by one.
Example
<script>
const user = {
name: 'neha',
age: 20,
courses: ['java', 'mysql']
}
for (const property in obj)
{
const value = obj[property]; // Read the value
console.log(property, value);
}
/*
output=>
name neha
age 20
courses ['java', 'mysql']
*/
Comparison
It is very simple to compare the primitive values in javascript. But comparing the objects is not so easy because objects are structured data. When we use ==
or ===
operator, they only compare the references of the objects.
Now, two objects can have the same key-value pairs but they can't occupy the same memory location. Let's see an example below:-
const user1 = {
name: 'neha',
}
const user2 = {
name: 'neha',
}
user1 === user2 // => false
user1 === user1 // => true
But what about properties? How we can compare them?🤔
The obvious way to compare objects by content is to read the properties and compare them manually.
For example-
function isUserEqual(obj1, obj2) {
return obj1.name === obj2.name;
}
const user1 = {
name: 'neha'
};
const user2 = {
name: 'neha'
};
const user3 = {
name: 'gauri'
};
isUserEqual(user1, user2); // => true
isUserEqual(user1, user3); // => false
Manual comparison requires manual extraction of properties — for simple objects, that’s not a problem. But to compare bigger objects (or objects of unknown structure), the manual comparison isn’t convenient because it requires a lot of boilerplate code.
Conclusion
In this blog post, we have discussed quite a few things about objects. Here are a few exercises for your better understanding of how objects work. You can try them,
1. Write a JavaScript program to list the properties of a JavaScript object.
Sample object:
var student = {
name : "David Rayy",
sclass : "VI",
rollno : 12 };
Sample Output: name, class, rollno
2. Write a JavaScript program to delete the rollno property from the following object.
Sample object:
var student = {
name : "David Rayy",
sclass : "VI",
rollno : 12 };
3. Write a function to deep compare two objects by value. What happens when the object’s values are functions? What about symbols?
That's it for object articles — all that remains now is for you to test your skills in the object assessment. If you enjoyed learning and find it useful please do like and share so that, it reaches others as well 🤝
Thanks for reading 😃
I would ❤ to connect with you at Twitter | LinkedIn | GitHub
Let me know in the comment section if you have any doubt or feedback.
Top comments (1)
It's just great, Keep up
Some comments have been hidden by the post's author - find out more