02. Creating object

There are several ways we can create objects. The first is by scratch, where we can assign it variables and functions in an on-the-go type of manner. The second way of creating an object has to deal with classes, which define sets of objects that share the same properties and methods.

Creating object properties on-the-go

A very simple way to create objects is to declare it as a new Object, then start assigning it properties and methods.

var carInstance = {}; 
var carInstace = new Object();  // same empty object created as above
carInstance.color = "blue";
carInstance.make = "Toyota";
carInstance.model = Camry";
carInstance.velocity = 0;
carInstance.drive = function() { this.velocity = 100; } 

Now we have a carInstance object with various properties and one method. As you can tell, this wouldn't be the best way to create objects, as there is no set standard.

Deleting object properties

To delete an object properties, use the delete keyword.

delete carInstance.color; // true if successfully deleted 


Classes define sets of objects that share the same properties and methods. In our example, it'll be best to define a particular Car class, then instantiate each car instance from that class. This way, our code is cleaner and each object shares the same properties and methods as others of its type.

function Car(color, make, model, velocity) {
  this.color = color;
  this.make = make;
  this.model = model;
  this.velocity = velocity;
  this.drive = function(speed) {
    this.velocity = speed;

Now we can call a Carobject, pass in parameters, and have our object(s) created with ease. Furthermore, this makes it much easier especially when we have to create multiple objects.

var myCar = Car("red", "porsche", "911 turbo", "100");
var yourCar = Car("black", "BMW", "X5", "120");

Build modern and responsive webpages

JavaScript & JQuery

Build modern and responsive webpages Try Front-end

This book was written for anyone who wants to use JavaScript to make their websites a little more interesting, engaging, interactive, or usable. In particular, it is aimed at people who do not have a degree in computer science (well, not yet anyway).

$ Check price
39.9939.99Amazon 4.5 logo(385+ reviews)

More Front-end resources

Aching back from coding all day?

Foam Seat Cushion

Aching back from coding all day? Try Back Problems

This foam seat cushion relieves lowerback pain, numbness and pressure sores by promoting healthy weight distribution, posture and spine alignment. Furthermore, it reduces pressure on the tailbone and hip bones while sitting. Perfect for sitting on the computer desk for long periods of time.

$ Check price
99.9599.95Amazon 4.5 logo(9,445+ reviews)

More Back Problems resources