JavaScript Objects in Depth

Code Morning!

JavaScript is an object oriented language. But it’s not object oriented the way other modern programming languages are. It’s class-less and prototype-based object oriented language.

If you are a sincere follower of JavaScript language and its new features, you must be aware of the fact that ECMAScript 6 does have introduced classes in JavaScript but they are mere syntactic sugar. JavaScript still remains prototype-based behind the wall.

Being prototype-based, each object in JavaScript may serve the foundation of other objects. We will go through more details on prototypes and inheritance in JavaScript in some other post. Let’s focus on objects, their attributes and different ways they can be created.

I'm an Object

An object is a collection of properties having name-value pairs. The value of a property could be as simple as a string, integer or could be an object or even a function. When a property value is a function, then the property is called method.

Creating Objects

There are many ways an object can be created in JavaScript.

Using Object Literal

The simplest way to create an object is using object literal syntax. The statement below creates an object bear with four properties.

var bear = {color: "gray", age: 10, type: "sloth", origin: "India"};

Using New Keyword

The bear object can also be created with ‘new’ keyword and properties can be added later.

var bear = new Object();
bear.color = "white";
bear.age = 12;
bear.type = "polar";
bear.origin = "Ireland";

Using Constructor Function

Creating objects with object literal and new keyword is useful when you need a single object at any time. But in real world applications we create objects from a template with predefined properties and methods. We use classes in most of the modern object oriented languages to define the attributes and behavior of an object.

JavaScript uses a different approach called constructor functions to achieve the goal. A constructor function is defined like this:

function Bear(color, age, type, origin){
   this.color = color;
   this.age = age;
   this.type = type;
   this.origin = origin;
   this.describe = function(){
      console.log("I am a " + type + "bear from " + origin);
   }
}

Tip: It’s a good practice to start a constructor function name with capital letter.

The ‘this’ keyword in JavaScript represents the current object in scope. We can create new bears using this function as below:

var slothBear = new Bear("gray", 10, "sloth", "India");
var polarBear = new Bear("white", 12, "polar", "Ireland");

I have created a method describe in the constructor function that logs a message like “I am a polar bear from Ireland” to browser console. This method can be invoked using the objects created above.

You can see that the function above makes it possible to create n number of objects without having to define the object every time. Now assume that we want to change the describe method or want to add an extra method to all bear objects. How easy it is to just make the changes in constructor function and that will reflect in all the objects.

There are some other ways to create objects in JavaScript. One of them is using Object.create() method which was introduced in ECMAScript 5. Using prototype pattern is another way objects are created in JavaScript.

Both the options need some knowledge of JavaScript prototype based inheritance, so I will explain these two methods in detail in another post on prototypes and inheritance.

Accessing Properties of an Object

Properties of an object can be accessed using dot notation.

var myBear = new Bear("black", 10, "ursus", "North America");
var color = myBear.color; // Gets the color of the bear
myBear.age = 15; // Sets the age of the bear

While dot notation is the most common way to access object properties, JavaScript also supports bracket notation which is less common but useful when you have property names that contain spaces. Sounds awkward, but perfectly valid as JavaScript property names could be any valid identifiers or any valid JavaScript strings.

In below sample the property “first name” can’t be accessed using dot notation.

var myObj = {"first name": "Aneesh", age: "45"};
var firstName = myObj["first name"]; // Returns 'Aneesh'

Bracket notations are also useful when properties names are known only at run-time. You can use an identifier which may hold the property name at run-time and can be used to access the property value. See the sample:

var myObj = {"first name": "Amit", age: "33"};
var prop = "age";
console.log(myObj[prop]);

The property age is stored in variable prop which can’t be used with dot notation. So the statement myObj.prop will return undefined as there is no property named prop in object myObj. The bracket notation, however, will use the value of prop which is the string “age and so gives back the value 33.

Deleting Properties from an Object

A property can be deleted from an object using delete keyword. However, we can only delete non-inherited properties. Inherited properties are those who come from object’s prototype object. We will walk through prototype object and inherited properties in the post on inheritance and prototype.

Deleting an object:

var myObj = {name: "Harsha", age: 28};
console.log(myObj.age); // Prints 28
delete myObj.age; 
console.log(myObj.age); // Prints undefined

More about Objects

  • Almost everything in JavaScript is object other than primitive types like strings, numbers, booleans, null and undefined. Functions are objects. Arrays are objects.
  • JavaScript objects are mutable. That means they can be changed.
  • Objects are reference type. So a variable containing an object has the reference of the object, not the value.
var myObj = {};
var myOtherObj = myObj;

myOtherObj is not a different object. Both myObj and myOtherObj reference the same object in memory.

That’s all folks for now.  Leave your comments if you have any questions or suggestions. Did you find the post useful? Hit the share buttons and spread the words.

You might also be interested in:

Share This:

10 Comments

  1. giorgi

    it would be interesting if you write also about non object oriented part of javascript, basically basic syntax variables and types. I like the way you explained stuff here, easy to follow. good job.

  2. john

    I like how you strike balance of not writing too much and not overwhelming reader with too many details and yet providing info which is enough to grasp concepts and be useful for the reader. Keep on good job, will read other your work too

Leave a Reply