Objects in JavaScript
gladwinbusula
Posted on January 27, 2023
OBJECTS IN JAVASCRIPT
In JavaScript, an object is an unordered collection of key-value pairs. Each key value pair is called a property.
Key of a property can be a string and the value of a property can be any value, e.g. number, function or array.
JavaScript provides (many) exact number ways to create an object. Most commonly used is to use the object literal notation.
Literal notation
The following is an example of creating an object student using literal notation;
How to Create Objects in JavaScript
let student = {};
javascript
To create an object with properties, you use key-value in curly braces.
For example;
let studentDetails= {firstname} ’Gladwin’
let student=new object
Console.log (studentDetails);
javascript
The Student object has one property: firstName.
Object Constructor
How to access properties in Objects
The dot (.) notation
You can access a property in javascript objects by using a dot sign
syntax
objectName.Propety
javasript
The following illustrates how to use dot notation to access a property of an object.
objectName . propertyName
c
The following illustrates how to access the value of an object’s property using bracket/array-like notation.
objectName[ ‘propertyName’]
javascript
For example;
let student = {
firstName: ‘Gladwin’
console.log (student [firstName]);
javascript
Modifying the value of a property
To change the value of a property, you use the assignment operator (=).
For example:
let student ={
firstName: ‘Gladwin’
student.firstName= ‘Gladwin’;
console.log (student);
javasript
Adding a new property to an object
The following statement adds the adm no. property to the student object and assign 32919 to it;
student.adm no =32919;
console.log (student);
javascript
Deleting a property of an object
To delete a property in an object, you use the delete operator.
delete objectName. propertyName;
javascript
The following example removes the adm no. property from the student object.
delete student.adm no.;
javascript
Checking if a property exists
To check if a property exists in an object, you use the in operator;
propertyName in objectName
javascipt
The in operator returns true if the propertyName exists in objectName.
The following example creates a student object and uses the in operator to check if studentId property exists in the object.
let student= {
firstName: ‘Gladwin’
studentId: 6
};
console.log (studentId in student);
javascript
Posted on January 27, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.