Objects In Javascript
Jillian Mwangi
Posted on January 27, 2023
OBJECTS AND OBJECT METHODS IN JAVASCRIPT
An object is a non-primitive data type that allows one to store a collection of multiple data. Objects are also variables that contain many different values. In Javascript objects are different from other programming languages since you don’t have to create classes first.
How to create objects in JavaScript
const objectName = {
property1:value1,
property2:value2,
}
An example is;
const resident= {
name: “Bashenga”,
age: 30, };
console.log(person); //output==(name: ‘Bashenga’ , age: 20)
In this example, a new object ‘resident’ has been created. ‘name’ and ‘age’ are the properties that belong to the object while ‘Bashenga’ and ‘30’ are the values that have been assigned to it.
Accessing object properties
There are two ways of accessing object properties ie;
Using dot notation
The syntax for accessing properties using dot notation is objectName.key
e.g using the previous example;
console.log(resident.name); //output== ‘Bashenga’
Using Bracket notation
The syntax used is objectName[“propertyName”]; e.g,
Console.log(resident (“name”)); //output== ‘Bashenga’
Object Methods in Javascript
A method is an object property that has a function value. They can also be referred to as actions that can be performed on an object. Methods are stored as properties.
example:
const resident= {
name: “Bashenga”,
age: 30,
greet:function () {console.log(‘Hello’)};}//the ‘greet’ property contains a function value.
Above is an object containing a method.
Accessing Object methods
Methods can also be accessed using the dot notation way, ie; objectName.methodName()
Eg using the previous example
resident.greet() //output== hello
If you try to access the method without including the brackets () ,it will give a function definition instead.
Eg resident.greet //output== function() {console.log(‘Hello’)}
Adding a Method to an Object
Example;
Let resident = {};
resident.name= “Bashenga”; //adding a property
resident.greet= function() {console.log (“hello”) }; //adding a method
In the above example, an object named ‘resident’ has been created then the ‘greet’ method was added to it.
You can use this method to add methods (or properties) to objects.
The ‘this’ keyword
The ‘this’ keyword is used to access properties of an object within the method of the same object.
This is the syntax used: this.propertyName
Eg
const resident= {
name: ‘Bashenga’,
age: 30,
greet: function(){console.log(‘The name is’ + ‘ ‘ + this.name)};
}; // output== The name is Bashenga
Posted on January 27, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.