Hello everyone, in this module, I will be discussing object in JavaScript. In the previous module, we discussed arrays in JavaScript. Now, it’s time to learn about objects in JavaScript. So, let’s begin.
Object in JavaScript
An object is a real-world entity having some properties and methods. For example, a student, a car, a pen, etc. In JavaScript, an object is defined as a collection or group of properties.
Each property is in the form of key-value pairs. The key is a string or number and is also known as a property name and the value can be anything like the number, Boolean, method, etc.
Creating an object in JavaScript
In JavaScript, an object can be created in 3 ways:
Using Object Literal in JavaScript
The property or key name is separated by a colon(:).
Syntax
var object_name={property1:val1,property2:val2,…..}
property1, property2, …. and val1, val2,…… are properties and values respectively.
var student={name:'Rahul',age:22,gender:'M'}; console.log(student); console.log(typeof student); //Output //{name: "Rahul", age: 22, gender: "M"} // object
We can also first declare the object and then assign properties and values to it.
let student={}; student['name']='Rahul'; student['age']=22; student['gender']='M'; console.log(student) //Output //{name: "Rahul", age: 22, gender: "M"}
Using new keyword in JavaScript
We can create objects using new keywords in JavaScript.
Syntax
var object_name=new Object()
var student=new Object(); student.name='Shekhar'; student.age='21'; console.log(student); console.log(typeof student); //Output //{name: "Shekhar", age: "21"} //object
Object constructor in JavaScript
In this method, a function is created with arguments. A value is assigned to the arguments of the current object using this keyword.
Syntax
var object_name = new Function_name(param1,param2,…..)
param1, param2,….. are parameters and it is optional.
function student(name,age,gen) { this.name=name; this.age=age; this.gender=gen; } var simran=new student('Simran',22,'F'); var shikhar=new student('Shikhar',21,'M'); console.log(`Name:${simran.name}, Age:${simran.age} and Gender:${simran.gender}`); console.log(`Name:${shikhar.name}, Age:${shikhar.age} and Gender:${shikhar.gender}`); //Output // Name:Simran, Age:22 and Gender:F // Name:Shikhar, Age:21 and Gender:M
The above method is useful when compared to the object literal and new keyword because it allows you to create multiple objects which are having the same properties. Hence, this method allows reusing the code. I will be discussing object literal in this module, which is mostly used.
How to access the properties of objects in JavaScript?
Using object name and property name or key in JavaScript
Syntax
Object_name.property_name
var employee = { name:'Himanshu Verma', age:25, salary:30000, gender:'M' }; console.log('Name:',employee.name); console.log('Age:',employee.age); console.log('Salary:',employee.salary); console.log('Gender:',employee.gender); //Output //Name: Himanshu Verma //Age: 25 //Salary: 30000 //Gender: M
Using object name and property name or key in JavaScript
Syntax
Object_name[property_name]
var employee={ name:'Himanshu Verma', age:25, salary:30000, gender:'M' }; console.log('Name:',employee['name']); console.log('Age:',employee['age']); console.log('Salary:',employee['salary']); console.log('Gender:',employee['gender']); //Output //Name: Himanshu Verma //Age: 25 //Salary: 30000 //Gender: M
Using Predefined Methods in JavaScript
JavaScript has predefined methods to get the key and values separately.
keys()
It is an object method used to get all the key names of an object. It uses the Object keyword.
Syntax
Object.keys(object_name)
console.log(Object.keys(employee)); //Output //["name", "age", "salary", "gender"]
values()
It is an object method used to get all the values of an object. It uses the Object keyword.
Syntax
Object.values(object_name)
console.log(Object.values(employee)); //Output //["Himanshu Verma", 25, 30000, "M"]
Function inside object in JavaScript
We can also use a function as a value in an object.
var info = { fname:'Surya', mname:'Pratap', lname:'Raj', age:function(){ return 21; } }; console.log('Name:'+info.fname+' ',info.mname+' '+info.lname); // calling a method console.log('Age:'+info.age()); // Output // Name:Surya Pratap Raj //Age:21
To use the property inside a method, we need to use this keyword in JavaScript.
var info={ fname:'Surya', mname:'Pratap', lname:'Shetty', name:function(){ return `My name is ${this.fname} ${this.mname} ${this.lname}.` } }; console.log(info.name()); //Output //My name is Surya Pratap Shetty.
Updating the values of a property in JavaScript
We can easily update the property values of an object by using the syntax shown below:
Syntax
Object_name.property_name=new value;
let info = { name:'Rakesh', age:21 }; console.log(info.name); console.log(info.age); info.age=30; console.log(info.age); //Output //Rakesh //21 //30
We can add new properties to the existing object.
let info={ name:'Rakesh', age:21 }; console.log(info); info.gender='M'; console.log(info); //Output //{name: "Rakesh", age: 21} //{name: "Rakesh", age: 21, gender: "M"}
Deleting the property of an object in JavaScript
We can delete the specific property of an object using the delete keyword in JavaScript.
Syntax
delete object_name.property_name
let info={ name:'Rakesh', age:21 }; console.log(info); delete info.age console.log(info); //Output //{name: "Rakesh", age: 21} //{name: "Rakesh"}
Array inside object in JavaScript
An array can be used inside an object.
let employee={ name:'Kartik Sharma', age:65, salary:30000, skills:['PHP','Java','JavaScript','HTML5'] }; console.log(employee.skills); console.log(employee.skills[2]); console.log(employee.skills[1]); //Output //["PHP", "Java", "JavaScript", "HTML5"] //JavaScript //Java
Nested object in JavaScript
An object can be used inside another object.
let employee = { name:'Kartik Sharma', age:65, salary:30000, address:{ city:'GM Road', state:'Mumbai', country:'India' } }; console.log(employee.address); console.log(`Address:${employee.address.city},${employee.address.state},${employee.address.country}.`); //Output // {city: "GM Road", state: "Mumbai", country: "India"} // Address:GM Road,Mumbai,India.
Array of objects in JavaScript
In JavaScript, an array can also be used to store multiple objects.
var student=[ {name:'Pallavi',age:21,gender:'F',course:'Machine learning'}, {name:'Shikhar',age:22,gender:'M',course:'Web development'}, {name:'Pankaj',age:22,gender:'M',course:'Android development'}, ]; for(let i=0;i<student.length;i++) { console.log('Name:',student[i].name); console.log('Age:',student[i].age); console.log('Gender:',student[i].gender); console.log('Course:',student[i].course); console.log('----------------'); } //Output //Name: Pallavi //Age: 21 //Gender: F //Course: Machine learning // ---------------- //Name: Shikhar //Age: 22 //Gender: M //Course: Web development // ---------------- //Name: Pankaj //Age: 22 //Gender: M //Course: Android development // ----------------
How to print key-value pairs using a for-in loop?
In JavaScript, just like any other loop, a for-in loop is used to print the property name or key and value of an object.
let info={ name:'Rakesh', age:21, gender:'M' }; for(let key in info) { console.log(key,':',info[key]); } //Output //name : Rakesh //age : 21 //gender : M
The entries() method in JavaScript
This method is used to return an array of key-value pairs of the object. It uses the Object keyword.
Syntax
Object.entries(object_name)
var student={ id:1, name:'Aman Roy', }; console.log(Object.entries(student)); //Output //[ [ 'id', 1 ], [ 'name', 'Aman Roy' ] ]
I hope Object in JavaScript module will be beneficial for you. Now, you might have gained a good knowledge of objects in JavaScript and will try to implement it by yourself. Keep Practicing!