JavaScript (JS) Objects
How to create a JavaScript (JS) Object?
An object in JS is an entity that contains properties and methods. JS is an object based langauge. In JS, we don’t create class to get the objects, instead we directly create objects.
// Creating an empty object
const obj = {}
console.log("Object is :", obj) // Output : Object is : {}
// Adding properties (assigning data) after creating an object :
const car = {}
car.type = "SUV"
car.model = "Seltos"
console.log("Object is :", car) // Output : Object is : { type: 'SUV', model: 'Seltos' }
Dot Vs Bracket Notation
Property value of an object can be accessed using dot . notation or brackets [ ]. It is very flexible to access object properties in JS. Syntax – objectName.propertyName OR objectName[“propertyName”]
console.log("Car type is :", car.type) // Output : Car type is : SUV
console.log("Car model is :", car["model"]) // Output : Car model is : Seltos
//Consider there is a property of an object, that starts with a number. For example,
const hosp = {
name: "AIMS",
24: "Hours"
}
console.log("Operating time :24 ", hosp["24"]) // Operating time :24 Hours
console.log("Operating time :24", hosp.24) // compilation error
// Consider a scenario where you want fetch value of object property but you are not sure about the property name. This property name can be a part of variable.
// For example,
const hosp = {
name: "AIMS",
24: "Hours",
city: "Mumbai"
}
const prop = "city" // During execution, name of the property (‘city’) is passed to a variable (‘prop’) & then we can use this variable to fetch value of property.
console.log(hosp[prop]) // Output : Mumbai
console.log(hosp.prop) // output : undefined
// Here we cannot use dot : hosp.prop
// This is because JS is unable to find value of ‘prop’ property. As prop property is not present (it is a variable in this case), we are getting output as undefined.
Adding Functions Inside JS Object
Objects can also have methods. These methods are part of object properties.
const hosp = {
name: "AIMS",
24: "Hours",
city: "Mumbai",
displayDetails : function displayHospitalDetails(){
console.log(`${hosp.name} hospital is located in ${hosp.city} city`)
console.log(`Operating hours are 24 ${hosp["24"]}`)
}
}
hosp.displayDetails()
// Output :
AIMS hospital is located in Mumbai city
Operating hours are 24 Hours
// Another way of defining object method without property name is as follows :
const hosp = {
name: "AIMS",
24: "Hours",
city: "Mumbai",
displayHospitalDetails(){
console.log(`${hosp.name} hospital is located in ${hosp.city} city`)
}
}
hosp.displayHospitalDetails() // Output : AIMS hospital is located in Mumbai city
‘this’ Keyword in Objects
‘this’ keyword refers to an object in JS. We cannot change its value as it is not a variable.
const hosp = {
name: "AIMS",
24: "Hours",
city: "Mumbai",
displayHospitalDetails(){
console.log(`${this.name} hospital is located in ${this.city} city`)
}
}
obj = hosp
console.log(obj)
obj.displayHospitalDetails()
// Output :
{
'24': 'Hours',
name: 'AIMS',
city: 'Mumbai',
displayHospitalDetails: [Function: displayHospitalDetails]
}
AIMS hospital is located in Mumbai city
How to Add/Delete/Update Object Properties?
There are various operations we can perform on the object properties, let us consider below examples.
const car = {
type:"SUV",
model:"Seltos",
color:"white",
condition:"new"
}
car.weight = "1300kg" // added new object property
car["regirstrationYear"] = 2022 // another way of adding object property
car.weight = "850kg" // Update object property
delete car.condition // Delete object property
console.log("Object is :", car)
// Output :
Object is : {
type: 'SUV',
model: 'Seltos',
color: 'white',
weight: '850kg',
regirstrationYear: 2022
}
Nested Objects
We can define functions, arrays and even objects inside of an object in JS.
const employee = {
firstName:"Swapnil",
lastName:"Mirkute",
age:30,
address:{
addressLine1:"290g Baker St",
addressLine2:"09 Flr",
city:"London",
postalCode:8901,
country:"UK"
}
}
console.log(employee)
console.log("---------------------------------")
console.log(employee.address)
// Output :
{
firstName: 'Swapnil',
lastName: 'Mirkute',
age: 30,
address: {
addressLine1: '290g Baker St',
addressLine2: '09 Flr',
city: 'London',
postalCode: 8901,
country: 'UK'
}
}
---------------------------------
{
addressLine1: '290g Baker St',
addressLine2: '09 Flr',
city: 'London',
postalCode: 8901,
country: 'UK'
}
//Accessing specific property of an object inside another object.
console.log(employee.address.country) // output : UK
//Adding object property for nested object :
employee.address.zone = "prime"
console.log(employee)
// Output :
{
firstName: 'Swapnil',
lastName: 'Mirkute',
age: 30,
address: {
addressLine1: '290g Baker St',
addressLine2: '09 Flr',
city: 'London',
postalCode: 8901,
country: 'UK',
zone: 'prime'
}
}
'For...in' Loop on JavaScript Objects
We can iterate over the properties of the object using for..in loop.
const bankAccount = {
type: "savings",
currency: "SGD",
balance: 9000,
}
console.log("Printing object property names :")
for (const key in bankAccount) {
console.log(key)
}
console.log("Printing values of object properties :")
for (const key in bankAccount) {
console.log(bankAccount[key]) // printing values of object properties
}
// Output :
Printing object property names :
type
currency
balance
Printing values of object properties :
savings
SGD
9000
Assignment
- Create an object in JS with property as Month numbers and values as Month names. Print all the months after June.
- Create an object ‘employee’ in JS with below mentioned property values. Update salary by 10% if yearsOfExperience is greater than 4 years.
- Name : “Swapnil”
- educationalQualification : “Computer Engineering”
- yearsOfExperience : 5
- salary : 50000
- Create an object ‘hosp’ in JS with a function definition as a property. Pass values to this function to update object property values using ‘this’ keyword. Refer this object :
- name
- city
- displayHospitalDetails(hospName, hospCity) // hostName & hospCity will be passed to this function from outside of an object to update ‘name’ & ‘city’ using ‘this’ keyword.