How to Create and Access an Object in Javascript


An object in Javascript is a variable that groups together a set of variables and/or funcdtions to create a model of something that resembles something from the real world.

The variables which make up the object are referred to as properties of the object.

For example, let's take as an example a house.

The house has an address, color, a certain number of bedrooms, a certain number of bathrooms, number of kitchens, and may or may not have a pool.

Below, we create an object in Javascript named house1 and we supply these properties to the house. We add in a function into this object that returns the total number of rooms in the house, which includes the number of bedrooms, bathrooms, and kitchens added together.

So you can see that we have create an object named house1.

The house has several properties, including an address, color, bedrooms, bathrooms, kitchens, and a function named totalRooms, which adds up all the rooms in the house.

Notice how these properties don't require the var declaration. Unlike true variables, properties of an object do not require the var declaration.

An object groups together any various types of variables along with functions to model a real-world object.

The first variable, address, is a string.

The second variable, color, is a string.

The bedrooms, bathrooms, and ktichens variables are integers.

We then have a function named totalRooms(), which adds the bedrooms, bathrooms, and kitchens variables together.

We then want to access and output these properties.

We do this by referencing the name of the object, followed by the dot operator (.), followed by the name of hte property.

To reference the house address, we use, house1.address

To reference the house color, we use, house1.color

To reference the house bedrooms, we use, house1.bedrooms

To reference the house bathrooms, we use, house1.bathrooms

To reference the house kitchens, we use, house1.kitchens

In order to invoke the totalRooms() function, we use, house1.totalRooms()

We output the house address, house color, the house bedrooms, the house bathrooms, the house kitchens, and the total rooms of the house using the console.log() function.

Running this program gives us the following output shown below.

And this is how to create and access an object in Javascript.

HTML Comment Box is loading comments...