JavaScript - Objects

Objects are a fundamental data structure in JavaScript that stand in for data collections.

Like a pen, pencil, car, knife, and fork, there are other things with a variety of characteristics and actions in the actual world. The same is true for JavaScript, where objects have a variety of properties and methods that enable manipulation and querying.

Strings and arrays are just two examples of the types of data that may be turned into JavaScript objects.

Creating JavaScript Objects

There are few ways for creating objects in JavaScript. Let's examine each of them individually:

Object Literal

The simplest way to declare and create a JavaScript object is with an object literal.

Suppose our goal is to create a Car object.

We are aware of the car's characteristics. Doors, colour, brand, speed, etc.

As a result, we will declare a Car object with the following properties:

var car ={
    name:"BMW",
    
    numberOfDoors:4,
    
    color:"White"
};

The “name”, “numberOfDoors” and “color” are called properties.

The values of the attributes are "BMW," "4", and "White."

Therefore, we always define the attributes and their values in the object literal method.

Another option is to declare and build an empty object as follows:

var car= {};

An empty object, as you can see, has no properties or values. According to the instructions in later sections of this tutorial, we can add attributes and values.

Using the new keyword

The new keyword combined with the Object function is another approach to build a JavaScript object.

The code will read:

var car = new Object();

This code has produced an empty object for us.

Later on, we'll also look at how to give the object properties.

Using Object.create() method

When we want to construct an object from another existing object, this way of object creation is really helpful.

Two parameters are passed to the Object.create() method:

The first argument must be an object. It is the one from which we shall make our object.

An optional object that includes the properties to be added to the new object is the second parameter.

Let's imagine that we have a business with the name "My Company".

The company object will be:

var company={
    companyName:"My Company"
};

And we want to hire someone for this business. Therefore, the person is employed by "My Company" Company. Since they work for the same firm, we will use the "company" object we made rather than creating a new object from the start that contains the employee's name, age, and years of experience.

So the code will be:

var employee=Object.create(company,{
  name:{
    value:"John"
  },
  age:{
    value:32
  },
  yearsOfExperience:{
    value:6 
  }
 });

The "employee" object will now have access to all the "company" object's properties because we built it from the "company" object.

In other words, all we need to do to get the employee's employer's name is access it in the following manner:

console.log(employee.companyName);

Object constructor function

Using the object constructor function method is an additional option for creating objects.

An object constructor function: What is it? The template of a parent object, or the original object, is simply provided by this straightforward method, which we will utilize to build our derivative objects.

Let's take the example of creating numerous housing objects.

Our Florida-based home contains 4 bedrooms, 2 living rooms, 2 bathrooms, and 1 yard. Another property in Tokyo with three bedrooms, a living room, a bathroom, and a yard Another home in London with 6 bedrooms, 3 living rooms, 4 bathrooms, 2 yards, and so on...

So instead of creating 3 separate objects for the 3 houses, like this:

var house1={
          bedrooms:4,
          
          livingrooms:2,
          
          toilets:2,
          
          yard:1,
          
          location:"Florida"
          
          };

var house2={
          bedrooms:3,
          
          livingrooms:1,
          
          toilets:1,
          
          yard:1,
          
          location:"Tokyo"
          
          };
          
var house3={
          bedrooms:6,
          
          livingrooms:3,
          
          toilets:4,
          
          yard:2,
          
          location:"London"
          
          }

We can design a standard template for the dwellings. After all, they each have a location, a living room, a bathroom, a yard, and a bedroom.

Therefore, we will use the object constructor function method as follows to generate this template:

function House(numbBedrooms, numbLivingrooms, numbToilets, numbYard, location){

  // Object constructor properties
}

The House constructor begins with an upper-case "H" because the name of a function constructor should always begin in capital letters.

All the properties are added once the function constructor object has been created.

We'll see how to add and access JavaScript objects' attributes and methods in the section that follows. So pay attention. 😉

But for the moment, let’s suppose that we have all the properties inside the function, how can we create an object for every house?

All we need to do is use the keyword new to execute the function constructor object to build an object for each house.

function House(numbBedrooms, numbLivingrooms, numbToilets, numbYard, location){

// Object constructor properties

}
var house1= new House(4, 2, 2, 1, "Florida");
var house2= new House(3, 1, 1, 1, "Tokyo");
var house3= new House(6, 3, 4, 2, "London");

Therefore, we create an object for each house independently by calling the House function constructor and supplying it the desired location, yard, number of bedrooms, living rooms, and restrooms.

The values of the object's properties are passed as parameters to the function that creates the House constructor object.

Properties and Methods of an Object

A method is an action or function that an object can do, and an object's properties can be thought of as a description of that object.

Object Literal

We’ve seen how to create an object with the Object literal method.

var car ={
    name:"BMW",
    
    numberOfDoors:4,
    
    color:"White"
};

And we stated that the "name", "numberOfDoors", and "colour" are object attributes for the "vehicle" object, while the values for the properties are "BMW", "4", and "White".

So using this way to create properties is straightforward. The desired property's name must be added first, followed by a colon and the value.

Imagine that you want to give the automobile object new properties later on in your code for any reason. For example, you want to add the speed and the mileage properties.

To do that, all you have to do is to add the following code:

var car ={
    name:"BMW",
    
    numberOfDoors:4,
    
    color:"White"
};
car.speed="300km/h";
car.mileage="70000km";

The syntax for adding more properties to an object is to write the object name, in this case "car", followed by a dot, and then the name of the property.

So now, a car's attributes also include speed and mileage.

The same syntax is used to access the object's properties. Always include the name of the object, a dot, and the name of the property after the object's name.

Therefore, if we wish to show the car's name, colour, or how many doors it has... The following code will be added:

var car ={
    name:"BMW",
    
    numberOfDoors:4,
    
    color:"White"
};
car.speed="300km/h";
car.mileage="70000km";
console.log(car.name);
console.log(car.numberOfDoors);
console.log(car.color);
console.log(car.speed);
console.log(car.mileage);

Let's say that this car produces a lot of noise, and we want it to say that “I’m a white BMW and I make a lot of noise”.

To accomplish that, we will add a method—a straightforward function—to the object.

Therefore, we'll declare our object as follows:

var car ={
    name:"BMW",
    
    numberOfDoors:4,
    
    color:"White",
    
    noise: function(){
    
             return  "I'm a " + this.color + this.name + "and I make a lot of noise"
    
    }
};
console.log(car.noise());

As you have presumably seen, the method contains the keyword this. this refers to the actual object, which in this context is the car.

As a result, we used this rather than writing car.color or car.name because we were still within the object and wanted to call it from there. If we were outside the object, we would have utilized and referred to it as a "vehicle" as we did when we added the characteristics of speed and distance from outside the object.

With the new keyword

As we have seen, we can also create an object using the new keyword with the Object constructor.

Now, we'll use the same syntax as the Object literal function if we want to add some attributes to the empty object.

In other words, we include the name of the property, a colon, and then the property's value.

Let's imagine we wish to add the properties' construction year and purchase date. The code will so be:

var car = new Object();
car.yearOfConstruction=2015;
car.dateOfPurchase="25/12/2019";
console.log(car);

Which means yearOfConstruction and dateOfPurchase become now the object properties.

In this instance, we'll use the same syntax for adding properties to add a method to the object.

var car = new Object();
car.yearOfConstruction=2015;
car.dateOfPurchase="25/12/2019";
car.noise=function (){
return "I was purchased in " + this.dateOfPurchase;
}
console.log(car.noise());

Using Object.create() method

When utilizing the object.create() method, we may use the same syntax as before to add a property.

Consider adding the employee's pay as a property for the sake of illustration. The code will so be:

var employee=Object.create(company,{
  name:{
  
    value:"John"
    
  },
  
  age:{
  
    value:32
    
  },
  
  yearsOfExperience:{
  
    value:6
    
  }
  
 });
 
 employee.salary="5000 dollars";
 
 console.log(employee);

Similar to adding properties, all we need to do to add a method to our employee object is use the dot notation.

var employee=Object.create(company,{
  name:{
  
    value:"John"
    
  },
  
  age:{
  
    value:32
    
  },
  
  yearsOfExperience:{
  
    value:6
    
  }
  
 });
 
 employee.salary="5000 dollars";
 
 employee.shout=function(){
 
  return "In " + this.companyName + " the salary is good!"
  
 };
 
 console.log(employee.shout());

Object constructor function

The Object constructor function method, as we mentioned in the last example, enables us to establish a general template that we can use to generate our objects.

And we mentioned that we have three homes, each with its own amenities (living rooms, bedrooms, etc.).

Our objects, which are our houses, will generally have these qualities (bedrooms, living rooms, toilets), we will state in the template that we will design.

We'll add the following code to achieve that:

function House(numbBedrooms, numbLivingrooms, numbToilets, numbYard, location){

  this.bedrooms= numbBedrooms;
  
  this.livingrooms= numbLivingrooms;
  
  this.toilets= numbToilets;
  
  this.yard= numbYard;
  
  this.location= location;
  
}

Using this, we added the properties. We assigned values to the properties using the this.nameOfTheProperty notation and the fact that the parameters to the function are the values of the properties.

So now, as previously mentioned, we can create our objects:

function House(numbBedrooms, numbLivingrooms, numbToilets, numbYard, location){

  this.bedrooms= numbBedrooms;
  
  this.livingrooms= numbLivingrooms;
  
  this.toilets= numbToilets;
  
  this.yard= numbYard;
  
  this.location= location;
  
}
var house1= new House(4, 2, 2, 1, "Florida");
var house2= new House(3, 1, 1, 1, "Tokyo");
var house3= new House(6, 3, 4, 2, "London");

To clarify, let's take The new House (4, 2, 2, 1, Florida) as an example. The constructor object House will take the arguments we gave it, "numbBedrooms, numbLivingrooms, numbToilets, numbYard, location" and replace them with "4,2,2,1,Florida" for the first object, "3,1,1,1,Tokyo" for the second object, and so on.

The constructor will then produce the following results for the first object: this.bedroom=4, this.livingrooms=2, this.toilets=2, this.yard=1. As a result, we have our house1 object's full set of properties initialised.

And the keyword this here refers to House.

In this example, we merely added the properties to the House constructor; no methods were introduced.

What happens, though, if we want our house1, house2, or house3 objects to have methods?

We can, of course, easily add methods to our objects. We'll proceed as usual and use the dot notation.

Let's imagine we want to include a function that says, "Hey, welcome to the house!" as a method.

The code will so be:

function House(numbBedrooms, numbLivingrooms, numbToilets, numbYard, location){

  this.bedrooms= numbBedrooms;
  
  this.livingrooms= numbLivingrooms;
  
  this.toilets= numbToilets;
  
  this.yard= numbYard;
  
  this.location= location;
  
}
var house1= new House(4, 2, 2, 1, "Florida");
var house2= new House(3, 1, 1, 1, "Tokyo");
var house3= new House(6, 3, 4, 2, "London");


house1.greet=function(){
  return "Hey, Welcome to the house!"
  
}
console.log(house1);

As you can see, the greet() function has been added to our object, along with the house1 attributes, which are presented above.

Conclusion

The major feature of JavaScript is Objects. An important first step in becoming a web developer is learning how to use them.

This tutorial has shown us what an object is, how to add one, and how to access its properties and methods.

I sincerely hope that the majority of you find the approach covered here to be helpful. Thank you for reading, and please feel free to leave any comments or questions in the comments section below.

Post a Comment

0 Comments