JavaScript Objects : Working with Data
This article covers all the basic fundaments about the JavaScript objects that you must Know !
Introduction
Objects are the one of the core fundamental building block of the JavaScript. They provide a way to store, structure and manipulate data efficiently. Objects allow developers to group related data and function into single unit which make code more organized and reusable.
From representing real world entities like person and to managing complex data structures in web applications, objects play important role in modern javascript development. In this article we, will learn about what objects are and will cover key concepts such as object properties, methods and prototype-based inheritance.
Bu the end of this article you will have solid understanding about JavaScript objects. so, let’s start the journey of JavaScript objects.
What is object in JavaScript ?
In JavaScript, an object is collection of different types data, which stores data in key - value pairs , where each key - value pair is referred as property of the object.
The values in object can be strings, numbers, boolean, function or even other objects and keys of object is simply just like variable name.
In reals life objects can be things like :- cars, houses, persons, animals and any other thing. Let’s understand this concept by taking the real life person as object.
Consider the person object :-
Here, you can see that we created an object named person with properties
name: Alex
Father’s name: Mike
age: 26
employed: false
This is the example of javascript objects.
How to create object in JavaScript ?
Objects can be created using the mainly according to the three methods. The first is using Object literals / initializers. Second is using the object()
constructor and the last one is using the object.create()
method.
Let’s understand there methods in details one - by -one.
1. Using Object literals
It is the most common way to initialize an object in JavaScript. An object literals is a comma - separated list of zero or more key - value pairs of the object, enclosed in curly braces ( {}
).
The syntax of object literals is :-
const object_name = {
// Properties of the object separates by comma
};
The advantage of using object literals is that, you are able to quick create object properties in curly braces. Let’s see the following example :-
const person = {
name: "alex",
Father_name: "Mike",
age: 26,
employed: false
};
console.log(person);
// Output :- { name: 'alex', Father_name: 'Mike', age: 26, employed: false }
2. Using Object()
Constructor
We can also declare an object using the Object()
Constructor in JavaScript. The object() constructor turns the input into the object property. Generally, it’s behaviour depends upon the input’s type.
The object can be initialize or called with or without the new
keyword but, when we created function as object we have to use new
keyword with Object()
.
const person = new Object();
person.name = "Alex"; // explicityly giving properties to person object
person.age = 26;
console.log(person);
// Output :- { name: 'Alex', age: 26 }
3. Using Object.create()
method
The objects in JavaScript can also be created using the Object.create()
method. This is the static method for creating a new object, using an existing object as prototype of the newly created object.
Its’s syntax is :-
Object.create(proto)
Object.create(proto, propertiesObject)
See the following example for proper understanding
const person = {
name: "Raju",
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
// Creating a new object that inherits from 'person'
const student = Object.create(person);
student.name = "Alice";
student.greet(); // Output: "Hello, my name is Alice"
person.greet();
// Output :-
// Hello, my name is Alice
// Hello, my name is Raju
In above code, the student
object inherits the greet
function from the person
object.
The Object.create() is very useful for creating prototype based inheritance easily.
Visual Representation of the object
The following code and diagram will help help you understand how objects in javascript are represented visually.
const Person = {
name: "Alex",
age: 26,
height: 5.77,
employed: false,
fullName: { // this is how you create a property with funtion as a value
firstName: "Alex",
lastName: "Singh"
}
}
console.log(Person);
The visual representation of the above code :-
Accessing the properties of object
There are two ways by which we can access the properties of the object in javascript which are following as :-
dot notation
bracket notation
Let’ s understand these notations in detail :-
1. dot notation ( .
)
The dot ( .
) notation is the most commonly used and simpler method to access the properties of the object in JavaScript.
Syntax :-
objectName.propertyName
Example :-
const person = {
name: "Rahul",
age: 25,
country: "India"
};
console.log(person.name); // Output: Rahul
console.log(person.age); // Output: 25
console.log(person.country); // Output: India
2. Bracket ( {}
) notation
Bracket notation is more flexible than dot notation and allow access of object properties dynamically .
Syntax :-
objectName["propertyName"]
example :-
const person = {
name: "Rahul",
age: 25,
"full name": "Rahul Singh"
};
console.log(person["name"]); // Output: Rahul
console.log(person["age"]); // Output: 25
console.log(person["full name"]); // Output: Rahul Singh
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.
Adding new properties to object
We can add the properties to object without writing it into the curly braces. Or you can say we can add new properties to the existing object. This can be done by using the the dot operator.
const person = {};
person.name = "rahul"; // Adding propety to object (person)
person.age = "23"
console.log(person);
// Output :- { name: 'rahul', age: 23 }
Deleting the property of an object
We can also delete the existing property of an object using the delete
keyword. for example :-
// Syntax :- delete objectName.propertyName
const Person = {
name: "Alex",
age: 26,
height: 5.77,
employed: false,
fullName: { // this is how you create a property with funtion as a value
firstName: "Alex",
lastName: "Singh"
}
}
delete Person.height; // You can see in output the height key and it's value has been removed
console.log(Person);
// Output :- { name: 'Alex', age: 26, employed: false, fullName: { firstName: 'Alex', lastName: 'Singh' } }
Getting keys and values of the object
If we wanted to print all the keys of the objects or all the values of the object we can use Object.keys()
(for keys) and Object.values()
(for values ).
Object.keys()
:- TheObject.keys()
static method returns an array of a given object's own string-keyed key names. It’s syntax is :Object.keys(Objectname);
Example :-
const Person = { name: "Alex", age: 26, height: 5.77, employed: false, fullName: { // this is how you create a property with funtion as a value firstName: "Alex", lastName: "Singh" } } let Key_values = Object.keys(Person); // Return all the keys of Person object console.log(Key_values); // Output :- [ 'name', 'age', 'height', 'employed', 'fullName' ]
Object.values()
:- TheObject.values()
static method returns an array of a given object's own string-keyed property values. The syntax is :-Object.values(ObjectName);
Example :-
const Person = { name: "Alex", age: 26, height: 5.77, employed: false, fullName: { // this is how you create a property with funtion as a value firstName: "Alex", lastName: "Singh" } } let Values= Object.values(Person); // Return all the values of Person object console.log(Values); // Output :- [ 'Alex', 26, 5.77, false, { firstName: 'Alex', lastName: 'Singh' } ]
Checking whether property already exists or not
To check if property already exists in object or not, we can use two keywords which are :-
in
keywordhasOwn
static method
Let’s understand each in detail .
1. in
keyword
The return type of the keyword is boolean means, if value exits it will return true else false. It’s syntax is :-
propert_Name in object_Name
example :-
const Person = {
name: "Alex",
age: 26,
height: 5.77,
employed: false,
}
console.log("age" in Person); // Output : true
console.log("Father_name" in Person); // Output : false
2. hasOwn
static method
The Object.hasOwn()
static method returns true
if the specified object has the indicated property as its own property. If the property is inherited, or does not exist, the method returns false
. The syntax is :-
Object.hasOwn(object_name, property);
example :-
const Person = {
name: "Alex",
age: 26,
height: 5.77,
employed: false,
}
console.log(Object.hasOwn(Person, "name")); // Output : true
console.log(Object.hasOwn(Person, "Father_name")); // Output : false
NOTE :- Object.hasOwn()
is a replacement for Object.hasOwnProperty()
These are some basic methods of the objects. To see all the methods of the JavaScript objects visit MDN web Docs
How to iterate over Objects in JavaScript ?
Iteration means looping through the properties of the object one-by-one or you can say in linear sequence. The Objects in JavaScript can be iterate by using the following methods :-
Using
for..in
LoopUsing
Object.entries()
andmap()
methodUsing
Object.keys()
andforEach()
method
Let’s understand these methods in detail :-
1. Using for…in
Loop
The properties of the object can be iterated over using a for..in loop. This loop is used to iterate over all non-symbol iterable properties of an object.
Some objects may contain properties that may be inherited from their prototypes. So, hasOwnProperty()
can be used to check property belongs to object itself. To print the values of each key we can use kay as index of the object.
Syntax :-
for (let iterator_name in ObjectName) {
value = ObjectName[iterator_name ];
console.log(iterator_name , value);
}
Example :-
const Person = {
name: "Alex",
age: 26,
height: 5.77,
employed: false,
}
for(let key in Person){
value = Person[key];
console.log(`The key is ${key} and value is ${value}`);
}
/* Output is :-
The key is name and value is Alex
The key is age and value is 26
The key is height and value is 5.77
The key is employed and value is false */
2. Using Object.entries()
and map()
method
The Object.entries(
)
method is used to return an array of the object’s own string-keyed property pairs. The returned array is used with the map()
method to extract the key and value from the pairs.
The key and values from the key-value pair can be extracted by accessing the first and second index of the array pair. The first index corresponds to the key and the second index corresponds to the value of the pair.
Syntax :-
Object.entries(object_Name).map(any_name=> {
let key = any_name[0];
let value = any_name[1];
console.log(key, value);
});
Example :-
const Person = {
name: "Alex",
age: 26,
height: 5.77,
employed: false,
}
Object.entries(Person).map(entry => {
let key = entry[0];
let value = entry[1];
console.log(`The key is ${key} and value is ${value}`);
});
/* Output is :-
The key is name and value is Alex
The key is age and value is 26
The key is height and value is 5.77
The key is employed and value is false */
3. Using Object.keys()
and forEach()
method
As we know already, object.keys()
Method returns an array of keys of the object and forEach()
method is an array method that allows you to iterate over each element in the array. So, we can pass keys as index in object to get the value of the object and by this way we can iterate over the object.
This is very similar to Object.entries()
method with only minor chnages.
Syntax :-
Object.keys(object_Name).forEach(iterator_name => {
let value = object_name[iterator_name];
console.log(iterator_name , value);
});
Example :-
const Person = {
name: "Alex",
age: 26,
height: 5.77,
employed: false,
}
Object.keys(Person).forEach(key => {
let value = Person[key];
console.log(`The key is: ${key} and the value is: ${value}`);
})
/* Output is :-
The key is: name and the value is: Alex
The key is: age and the value is: 26
The key is: height and the value is: 5.77
The key is: employed and the value is: false */
So , these are the ways by which we can iterate over objects in javascript.
Conclusion
So, that’s it during the whole journey we learned a everything about the objects in JavaScript, staring form basic to iteration over objects. I Hope this article helps you to understand the one of the core fundamental of the javaScript (objects). If yes ! then, please like my article and let me know in comments if any suggestion by your side. So, that’ s it for today! Bye all….