JavaScript Time-Saving Tip: Preventing erroneous property creation


JavaScript is a dynamic language which makes it very powerful. We all know, ‘”With great power comes great responsibility’. Following this mantra, we must act responsibly when creating objects. We can do this by mimicking the static nature of the older class-based systems.

 

Take the following object construction for example:


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

This is a simple object with three properties: make, model and year. The object can be instantiated a couple of ways. The first being we can pass the parameter values as part of the constructor:


var car = new Car("Ford", "Capri", 1982);

console.log(car.make);
console.log(car.model);
console.log(car.year);

The result of the above is that the make, model and year values are printed to the browser’s console. The second method instantiates an empty object and sets the properties one-by-one:


var car2 = new Car();

car2.make = "Fiat";
car2.modal = "Punto";
car2.year = 1982;

console.log(car.make);
console.log(car.modal);
console.log(car.year);

This too prints the values of the properties to the console; however, those with an eye for detail will notice the example refers to a property labelled ‘modal’ instead of ‘model’ – a typing error! The result of which – due JavaScripts dynamic nature – ends up with a spurious property creation. The Car object will now include four properties: make, model, year and modal: not intended! This type of simple mistake could result in the failure of critical business logic that relies on the model property and hours of time could be wasted debugging the code. Don’t panic, courtesy of ECMAScript 5th Edition this is easily fixed with the following amendment to the object creation:


function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;

  Object.preventExtensions(this);
}

The highlighted line above will instruct the interpreter to prevent the creation of any additional properties after object construction. The typing error above will no longer create a new property and the console.log command will print undefined, in addition to this some interpreters will raise a TypeError.