JavaScript Object and it’s method

Table of contents

No heading

No headings in the article.

Objects are the most important data type in JavaScript. These objects are quite different from JavaScript's primitive data types like number, string, boolean, null and undefined. Because these data types can store only a single value in itself. But we can store multiple values of different data types in the object.

Syntax

let object_name = {

key: value,

key: value

}

Here is an example of a JavaScript Object.

let phone = {
Model : "iphone14",
Price : 138000,
isAvailable : true,
addToCart : function(){
           console.log("iphone14 was added to your cart"); 
} 

phone.addToCart();

In this example model, prices are the keys and iphone14 and 138000 are the values which refer to an object. the object can also contain a function in itself. We can access these keys and values through the object.

Object Methods

These object methods can be accessed through using functions. As we know functions are stored as property values. We can call these objects without brackets().

In a method, this keyword refers to the owner object and we can add additional information with the object method.

Syntax

Here is the syntax for the object method.

objectName.methodName()

// Object creation
        var Country = {
            name: "India",
            state : "Rajasthan",
            city : "Jaipur",

            cityDetails : function() {
                return this.name + " " + this.state
                    + " " + this.city + " ";
            }
        };

        // Display object data
        console.log(Country.cityDetails());

This is the example of object and its method.In above example we can see that country is a object which is having name, state and city as key and India, Rajasthan and Jaipur as value. Here is a method which is city details, which can be accessed through objectName.methodName() syntax and finally we can print the value through it.