The real-life understanding of the objects in JavaScript
Ashutosh
Posted on July 12, 2020
Why do we need objects?
In my last article, I spoke about how variables provide a limited scope and arrays helps us to input so many related data in a single array.
Taking the same example of friends, suppose we want to provide other supporting information of each friend like name, age, and city. Let's see how this can be achieved using an object.
var friends = ["John", "Raj", "Harry", "Zach"]; //Used earlier
var friend1 = ["John", 25, "LA"];
var friend2 = ["Raj", 27, "Mumbai"];
var friend3 = ["Harry", 26, "New York"];
var friend4 = ["Zach", 30, "England"];
//Suppose we want to access the city "Raj" lives in
console.log(friend2[2]); // Output --> "Mumbai"
//It is not very readable. If by mistake we change the order we will get the wrong answer.
var friend2 = ["Raj", "Mumbai", 27];
console.log(friend2[2]); // Output --> 27
We saw that it is very difficult to accommodate supporting information of the given friend. Also, accessing one's data using index numbers can be very confusing. To deal with this issue, the concept of Object is introduced which stores data in the form of key-value pairs and solves the problem as shown below.
Friends data stored as Object
var friend1 = {
name : "Zach",
age : 30,
city : "England"
};
Objects hold all sorts of data be it of type number, string, boolean, array, or even another object itself.
var dog = {
name : "Tommy",
age : 3,
hasEaten : true,
foodLiking : ["biscuits", "chapati milk", "rice chicken"],
friend : {
name : "Sunny",
age : 5,
owner: "Kami"
}
};
Creating Objects
There are few ways of initializing objects like an array.
var cat = {} //Empty Object
cat.name = "Meow";
cat.age = 4;
cat.food = ["milk", "cereal", "chapati"];
var dog = new Object();
dog.name : "Tommy";
dog.age : 3;
dog.hasEaten : true;
Retrieving data from objects
There are two ways to retrieve the existing data
Bracket Notation - It is similar to the array data retrieval.
Dot Notation - In this method, we retrieve the data using the dot operator.
Let's look at an example to have a better understanding
//Considering the same example that we took above
var friend1 = {
name : "Zach",
age : 30,
city : "England"
};
//Bracket Notation
console.log(friend1["name"]); // Output --> "Zach"
//Dot Notation
console.log(friend1.age); // Output --> 30
Updating objects
To update an object select the key and assign a new value to it.
var friend1 = {
name : "Zach",
age : 30,
city : "England"
};
friend1.age += 1; // Adding 1 to the age
friend1["city"] = "Chennai"; //Updating city using bracket notation
friend1.job = "Infosys"; //Adding new key-value pair to the object
Posted on July 12, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.