DEV Community

Cover image for Creating Objects in JavaScript.
Hozan
Hozan

Posted on

Creating Objects in JavaScript.

Last week I covered primitives values and objects and their differences, this week I will touch upon the topic of how to create objects using different syntaxes and summarise them here, so you can have a rough idea of how they can be created and the benefit of each syntax.

If you are beginner (like me) there is a high a chance that so far when you created objects you used the literal notation (also called Object Initializer), below is an example of an object created with literal notation:

var myCar = {
    carMake: 'Ford',
    carModel: 'Mustang',
    carYear: 1969
};
Enter fullscreen mode Exit fullscreen mode

but in JavaScript there is another way to create objects, using the constructor function. Below is an example of the same object as above created using the constructor functions:

function Car(make, model, year) {
  this.carMake = make;
  this.carModel = model;
  this.carYear = year;
}
var myCar = new Car('Ford', 'Mustang', 1969);
Enter fullscreen mode Exit fullscreen mode

To achieve that we have to do the following steps:

  1. Define the object type, in our case here the type is Car, and we defined it using a constructor function. Also note that there is a strong convention to name constructor functions with an upper-case first letter, hence we used Car and not car.

  2. Add this keyword to every property, when doing so it will assign values to the object's properties based on the values passed to the function.

  3. Create an instance of the object with new operator.

As you can see the advantage of using a constructor functions (with the help of new) is that you can create multiple and even hundreds new instances of the object type. Therefore, you can have multiple different objects with same properties and methods as shown below :

var car1 = new Car('Nissan', '300ZX', 1992);
var car2 = new Car('Mazda', 'Miata', 1990);
etc..
Enter fullscreen mode Exit fullscreen mode

However, when it comes to simple objects it is best to stick with literal notation as it is faster to run and easier to read since we do not need to instantiate it first like we do with constructor functions:

// constructor function:
var myCar = new Car('Ford', 'Mustang', 1969);
console.log(myCar.carMake)    //’Ford’

// literal notation
console.log(myCar.carMake)    //’Ford’
Enter fullscreen mode Exit fullscreen mode

These two syntaxes also have their difference when adding new methods or new properties.

To add a property or a method to a predefined object created with literal notation consider the following object:

var myCar = {
    carMake: 'Ford',
    carModel: 'Mustang',
    carYear: 1969
};
Enter fullscreen mode Exit fullscreen mode
  • Adding a property:

consider we want to add property color with a value equal to “black”, to achieve that we do the following east step:

myCar.carColor = “black”

Now we have the object modified and it will look like below :

var myCar = {
    carMake: 'Ford',
    carModel: 'Mustang',
    carYear: 1969;
    carColor: ‘black’
};
Enter fullscreen mode Exit fullscreen mode
  • Adding a method:

To do that, we define a property name (or key) with its value being a function definition:

myCar.carDetalis = function (){
      return this.carMake + “ “ + this.carModel;
}
Enter fullscreen mode Exit fullscreen mode

Note that we used this keyword when defining a method, it refers to the "owner" of the function. So in our case here the “owner” is myCar object, the property name is carDetails and the function definition is function () { return this.carMake + “ “ + this.carModel; }:

console.log(myCar.carDetails()); // ‘Ford Mustang’

To achieve what we did in the above examples when an object is created using constructor functions consider this object:

function Car(make, model, year) {
  this.carMake = make;
  this.carModel = model;
  this.carYear = year;
}

var myCar = new Car('Ford', 'Mustang', 1969);
var car1 = new Car('Nissan', '300ZX', 1992);
Enter fullscreen mode Exit fullscreen mode
  • Adding a property :

If you want to add a property to myCar then it very simple, it is the same when adding a property to an object created with literal notation.

myCar.carColor = “black” ;
console.log(myCar.carColor);  // ‘black’
Enter fullscreen mode Exit fullscreen mode

However this property will only be added to myCar object, and not any other objects created with the same construcuor function, so if you were to access such a property in car1 you will get undefined.

console.log(car1.carColor) // undefined

To add the new property to all objects created with the same constructor function , you have to add the property to the definition of the Car object type.

function Car(make, model, year, color) {
  this.carMake = make;
  this.carModel = model;
  this.carYear = year;
  this.carColor = color;
}
Enter fullscreen mode Exit fullscreen mode

However, there is another way around this if we want to add the new property which is simpler and quicker, especially if our script is hundred of lines long, we use Function.prototype.property , and this is only available to object's created with the constructor syntax.

Car.prototype.color = 'black';
console.log(car1.color);    // 'black'
Enter fullscreen mode Exit fullscreen mode
  • Adding a method:

Just like adding a property, it is also has similar approach. So you can either add the method to the constructor function itself or use Function.prototype.property , which will have the method avialbe to all objects created with the same function.

function Car(make, model, year, color) {
  this.carMake = make;
  this.carModel = model;
  this.carYear = year;
  this.carColor = color;
  this.carDetails = function (){
      return this.carMake + “ “ + this.carModel;
}

console.log(myCar.carDetails()) // ‘Ford Mustang’
console.log(car1.carDetails()) // ‘Nissan 300ZX’
Enter fullscreen mode Exit fullscreen mode

Or

Car.prototype.carDetails = function (){
      return this.carMake + “ “ + this.carModel;
}

console.log(myCar.carDetails()) // ‘Ford Mustang’
console.log(car1.carDetails()) // ‘Nissan 300ZX’
Enter fullscreen mode Exit fullscreen mode

If you want to know what the new operator does behind the scenes you can read this amazing article which also explains why we need it to create objects when using constructor functions.

If you have any suggestions or questions, leave them below.

Happy coding :) .

Top comments (0)