Understanding Objects in JavaScript
what is an object and why we need them ?
You know that array is used to store the list of items . But what happens if there are some other characteristics {like colour and weight etc } of that item and we need to store them . It gets complicated right ?
That's where the object comes into play!!!
In programming, an object is a special "container" that bundles together information(data) and actions (functions) that belong to the respective I
magine you are describing a person. In an array, it might look like this:var person = ["Ronak", 25, "Karnataka"]; .
Looking at that array, it’s hard to tell what "25" represents. Is it her age? Her favorite number? Her street address?
here comes the objects it allows you to use key-value pairs, giving every piece of data a label (the key) and a value. let us see further you will get know to more what object is .......
Creating an Object
We create objects using curly braces {}. In obove example:
var person = {
name: "ronak",
age: 25,
city: "karnataka"
};
here the name and age are known as keys and Ronak , 25 and karnataka are the values of the respective keys .
Accessing Properties
There are 2 types of accessing methods : Dot Notation and Bracket Notation .
***DOT NOTION
***The Dot Notation approach involves using a dot (.) and a key to access a property.
The syntax: object.key
from above example :var home = person.city // output : karnataka
By using dot and the city key, .name, we get "karnataka " which is the value of the city property.
BRACKET NOTION
The Bracket Notation approach involves using square brackets, in which you have an expression that evaluates to a value.
The syntax : object[expression]
from above example :var home = person["city"] // output : karnataka
By using square brackets and a "city" string expression, ["city"], we get "karnataka " which is the value of the city property.
Updating, Adding, and Deleting
It is as same as we used to do in array !
Updating:
person.age = 26;Adding:
person.isStudent = true;Deleting:
delete person.city;
Looping Through an Object
Sometimes you need to look at every "key" inside an object. For this, we use the for loop as we used to do in array .
for (var key in person) {
console.log(key + ": " + person[key]);
}
// This will print:
// name: ronak
// age: 26
// isStudent: true
lets see this what you have read untill now !!!
THANK YOU!!!
