In this blog we will learn about JavaScript (JS) Objects. As you know, JS is one of the most popular languages for web developers.
In JS , we can directly create the objects and we don’t write class to create the object of that classes. Similar to other programming languages JS is also Object oriented programming language, which complies or satisfy the below four principles object-oriented programming
- Polymorphism
- Encapsulation
- Inheritance
- Aggregation
An object is a collection of properties which can be defined as key/value pairs; where each property has been assigned with the key and the value, wherein the key in the property can be the string and value can be any value. Let’s learn more about JS objects.
JavaScript Objects Overview:-
Objects in JavaScript may be defined as an unordered collection of related data, of primitive or reference types, in the form of key/value pairs. These keys can be variables or functions and are called properties and methods, (respectively) in the context of an object.
All the objects in JS are derived from the parent Object constructors, and each object has many built-in methods.
Creating a JS Object:- We can create objects in 2 ways
- Object literals and Properties
- Object Constructor.
- By directly creating an object instance.
Object literals and properties:- Syntax for this is object={property1:value1,property2:value2.....propertyN:valueN}
let test = {..};
let emp = {
name: “Knowledge Hut”;
message: ”Hello World”;
};
The properties name and message is known as key and assigned with the value, whereas emp is the object.
property name value =”Knowledge Hut”
property message value= ”Hello World”;
Object Constructor:- In order to create an object using constructor, we need to create the function with arguments. Each argument value will be assigned to the current object, using the keyword this.
<script>
function student(studId, studName,studMarks){
this.studId=studId;
this.studName=studName;
this.studMarks=studMarks;
}
s=new student(1,"APJ Abdul Kalam",450);
document.write(s.studId+" "+s.studName+" "+s.studMarks);
</script>
Outputà1 APJ Abdul Kalam 450
By directly creating object instance:- We can create the object instance using the new keyword syntax for the same var objName = new Object();
<script>
var student=new Object();
student.studId=1;
student.studName="APJ Abdul Kalam";
student.studMarks=450;
document.write(student.studId+" "+ student.studName+" "+ student.studMarks);
</script>
Outputà1 APJ Abdul Kalam 450
JavaScript Objects and Properties:- Once we create an object, we can start adding the properties to the newly created objects.
let test = {
firstName: "Knowledge",
lastName: "Hut" };
In the above example firstname and lastname are the properties for the object test and “Knowledge” and “Hut” are the values.
Property name can be numbers and strings, when we are using numbers are property name we will be accessing them using the [] called as bracket notations.
let test = {
name: "APJ Abdul Kalam",
Country : "India",
birth year: '1987',
09 : 450,
printResult : function(){
console.log("The result of 09 is ${test["09"]}`); // here this is called bracket notation
}
}
test.printResult();
Output --> The result of 09 is 450
Property name with strings must be enclosed in quotes
let test = {
"emp name" : "APJ Abdul Kalam",
}
Inherited Properties:- Properties that are inherited from the existing object. To inherit the property we can use the method hasOwnProperty();
const test1 = new Object();
test1.prop1 = 111;
console.log(test1.hasOwnProperty('prop1')); // true
Attributes of Property:-
JS has 4 attributes
- Value:- Property value
- writable:- if true the value can be changed
- enumerable:- if true property can be iterated over an enumeration.
- configurable:- if false deletes/changes the property
Accessing JavaScript Objects:- All the JS object properties and members can be accessed using the dot notation (:). Syntax - (objectName.propertyName)
EX:emp.empFirstName
let emp ={
empFirstName: ‘APJ Abdul’,
empLastName:’Kalam’
};
console.log(emp.empFirstName);
console.log(emp.empLastName);
Array Notation:- Accessing object’s property via array like notation.
Syntax—objectName[‘propertyName’];
let emp ={
empFirstName: ‘APJ Abdul’,
empLastName:’Kalam’
};
console.log(emp[empFirstName]);
console.log(emp[empLastName]);
If a property contains a name space we need to place the same in quotes.
let emp ={
‘emp salary’: 25,000,
empFirstName: ‘APJ Abdul’,
empLastName:’Kalam’
};
While accessing the property which has namespace we must always use array like notation, the dot notation will give error.
emp[‘emp salary’];
Changing the property Value:- Using assignment operator we can change the value of the property.
let emp ={
empFirstName: ‘Abdul’,
empLastName:’Kalam’
};
emp.empFirstName = ‘APJ’;
console.log(emp); àOutput à{empFirstName: ‘APJ’, empLastName:’Kalam’}
Adding new property to the object:- Once the object has been created we can add a property to the object.
emp.id = 1243;
Deleting a property:- Using delete operator we can delete a property from the object.
Syntax—delete objectName.propertyName;
Ex-delete emp.id;
To check if property exists:- Using in operator we can check if any particular property exists in the object or not.
Syntax- propertyName in objectName
let student ={
studentFirstName: ‘APJ Abdul’,
studentLastName:’Kalam’,
studentPanNo:101234,
};
console.log(studentId in student);
console.log(studentPanNo in student);
Output false true
Iterate using for..in loop:-
Syntax – for(let key in object){ ///….
};
The this keyword:- Using this we can access the data stored in the objects.
Syntax- this.propertyName
let student ={
studentFirstName: ‘APJ Abdul’,
studentLastName:’Kalam’,
studentPanNo:101234,
msg:function(){
console.log(‘Welcome to school’);
},
getStdName: function(){
return this. studentFirstName+ ‘ ’+this. studentLastName;
}
};
console.log(student. getStdName());
output APJ Abdul Kalam
JavaScript Object Methods:- All the objects have actions as long as actions are used inside the functions.Methods are defined in the same way that normal functions are defined, except that they have to be assigned as the property of an object.
var objectName = {
method1: function(params) {
// ...do something
}
method2: function(params) {
// ...do something
}
};
OR
var objectName = {
method1(params) {
// ...do something
}
method2(params) {
// ...do something
}
};
OR
var objectName.method1 = {
// ...do something
}
let student ={
studentFirstName: ‘APJ Abdul’,
studentLastName:’Kalam’,
studentPanNo:101234,
};
Student.message =function(){
console.log(‘Welcome to School’);
}
Student.message();
Output Welcome to school
Build in JS Object methods:- Here are some JS built-in objects and their usage:
- Object.assign() -- Used to copy own properties from source to destination object.
- Object.create() – Used to create the new object and link to an existing object.
- Object.keys() – Used to create an array of keys of an object, we can also iterate through the keys of the object.
- Object.values() – Used to create an array of values of an object, we can also iterate through the values of the object.
- Object.entities() – Used to return the array of keys/values of an object. Object.freeze() – Used to prevent removal of the existing properties of the object.
Defining getters and setters:- The getters and setters of the object are known as accessor properties. With the help of getters and setters, security is improved and malicious tampering of code is prevented.
Syntax—
let obj = {
get propName() {
// getter, the code executed on getting obj.propName
},
set propName(value) {
// setter, the code executed on setting obj.propName = value
}
};
Get:
let student ={
studentFirstName: ‘APJ Abdul’,
studentLastName:’Kalam’,
get studFullName() {
return `${this.studentFirstName} ${this.studentLastName}`;
}
};
console.log(student.studFullName);
Set:-
let student ={
studentFirstName: ‘APJ Abdul’,
studentLastName:’Kalam’,
get studFullName() {
return `${this.studentFirstName} ${this.studentLastName}`;
},
set studFullName(value){
[this. studentFirstName, this. studentLastName] = value.split(" ");
}
};
student.studFullName = “APJ Abdul Kalam”;
console.log(student.studFullName);
Conclusion:
In this blog we explored JS objects. JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a key and a value. A property's value can be a function, in which case the property is known as a method. Objects can be accessed either by dot(.) notation or array-like notation([]). JS Objects are mutable, which means that their state can be modified after they have been created. An object provides us the ability to read our code more effectively and clearly.