In this article, we will understand JavaScript objects and how to use it.
What is JavaScript Object?
JavaScript Objects are containers where properties are stored. let's say we have a kitchen and its accessories inside. the kitchen itself is called JavaScript Object while the accessories and anything that concern the kitchen are properties of the object.
The image below shows how a JavaScript object is been created.
let houseObject = {
ownerName: "Emmanuel",
location: "galadima, gwarimpa",
country: "nigeria",
numberOfpeopleLiving: 1,
isCitizen: true,
}
console.log(houseObject)
//output : {ownerName: "Emmanuel", location: "galadima, gwarimpa", country: "nigeria", numberOfpeopleLiving: 1, isCitizen: true}
How to access the object and get a property
in JavaScript, we use dot notation to access any properties created in an object.
let houseObject = {
ownerName: "Emmanuel",
location: "galadima, gwarimpa",
country: "nigeria",
numberOfpeopleLiving: 1,
isCitizen: true,
}
console.log(houseObject.ownerName)
//output: Emmanuel
console.log(houseObject.isCitizen)
//output: true
A JavaScript object can have an array, a function, and also another object inside.
this how it look like
let houseObject = {
ownerName: "Emmanuel",
location: "galadima, gwarimpa",
country: "nigeria",
numberOfpeopleLiving: 1,
isCitizen: true,
houseAccessories:["bed", "televison", "chair"],
getObjectProperty: () => {
return houseObject.ownerName + "is the owner of the house"
},
kitchenObject:{
kitchenColor:"red",
kitchenAccessories: ["spoon", "gas cooker", "plate"]
}
}
console.log(houseObject.getObjectProperty())
//output: Emmanuel is the owner of the house
console.log(houseObject.houseAccessories)
//output: ["bed", "televison", "chair"]
console.log(houseObject.kitchenObject)
// output: {kitchenColor:"red",kitchenAccessories: ["spoon", "gas cooker", "plate"]}
That’s the end of this article. thanks for checking it out