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


Build modern and responsive webpages Try Front-end

This book teaches HTML as if it's for anyone - hobbyists, students, and professionals - and it's full-color throughout. It utilizes information graphics and lifestyle photography to explain the topics in a simple way that is engaging. You can progress through the chapters from beginning to end or just dip into topics of particular interest at your leisure.

$ Check price
29.9929.99Amazon 4.5 logo(926+ reviews)

More Front-end resources

Aching back from coding all day?

Self-Massage Tool

Aching back from coding all day? Try Back Problems

Relieve spasms, tight muscles, trigger points and pressure points with the Body Back Buddy! This trigger point massage is designed to help you self-message any area of your body - especially those that are hard to reach. Keeping your muscles relaxes and out of contraction is importan in helping to reduce pain and prevent muscle injury.

$ Check price
29.9529.95Amazon 4.5 logo(3,443+ reviews)

More Back Problems resources