Objects in JavaScript
JavaScript consists of various Data Types like String, Number, Boolean, Objects etc. This article will talk about Objects in JavaScript.
What is an Object?
Object in JavaScript is a non-primitive Data Type which can store multiple collections of data. Objects are written as key : value pairs. JavaScript objects can be compared to objects in real life which is also the case in other programming languages. Compare it with a car for example. A car has a color, weight, number of seats, material it is made of, type of suspension system etc.
Object Declaration
Objects in JavaScript can be declared in two ways:
const objectName = {
key1 : value1,
key2 : value2,
key3 : value3
};
Example:
const car = { brand : 'Tata', name : 'Nexa', color : 'Red' };
Or
const objectName = new Object();
objectName.key1 = "value";
Example:
const car = new Object();
car.brand = 'Hyundai';
car.name = 'Creta';
Accessing Properties of an Object
The properties of an Object in JavaScript can be accessed in two ways:
objectName.property;
//example:
car.brand;
Or
objectName["property"];
//example:
car["brand"];
Object Methods
JavaScript language has many methods that can be used with the objects. Below are few of the methods you can try:
1. Object.keys()
This method returns an array of keys of the specified Object.
Example:
const car = { brand : 'Tata', name : 'Nexa', color : 'Red' };
console.log(Object.keys(car));
The expected output of the above would be ["brand","name","color"].
2. Object.values()
This method returns an array of values of the specified Object.
Example:
const car = { brand : 'Tata', name : 'Nexa', color : 'Red' };
console.log(Object.values(car));
The expected output of the above would be ["Tata","Nexa","Red"].
3. Object.entries()
This method returns an array of [key, value] pairs of the specified Object.
Example:
const car = { brand : 'Tata', name : 'Nexa', color : 'Red' };
for (const [key, value] of Object.entries(car)) {
console.log(`${key}: ${value}`);
}
The expected output of the above would be "brand: Tata", "name: Nexa", "color: Red".