JavaScript Object in Detail
August 19, 2018
, ,

JavaScript is an object-based language based on prototypes, rather than being class-based.It’s not object oriented the way other modern programming languages are. Because of this different basis, it can be less apparent how JavaScript allows you to create hierarchies of objects and to have inheritance of properties and their values. This chapter attempts to clarify the situation.

What is 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.

Consider this example of object:

var person = {firstName: “John”, lastName: “Doe”};

Think of an object as a list that contains items, and each item (a property or a method) in the list is stored by a name-value pair. The property names in the example above are firstName and lastName. And the values are “John” and “Doe.”

Property names can be a string or a number, but if the property name is a number, it has to be accessed with the bracket notation. More on bracket notation later. Here is another example of objects with numbers as the property name:

  1. var ageGroup = {17: “Children”, 20:”Adult”};
  2. console.log(ageGroup.30) // This will throw an error
    // This is how you will access the value of the property 30, to get value “Children”
  3. console.log(ageGroup[“30”]); // Children
    //It is best to avoid using numbers as property names.

Class in Javascript:

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.

Creating Objects

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

Using Object leterals:

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

  1. 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.

  1. var bear = new Object();
  2. bear.color = “white”;
  3. bear.age = 12;
  4. bear.type = “polar”;
  5. 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:

  1. function Bear(color, age, type, origin){
  2.   this.color = color;
  3.   this.age = age;
  4.   this.type = type;
  5.   this.origin = origin;
  6.   this.describe = function(){
  7.      console.log(“I am a ” + type + “bear from ” + origin);
  8.   }
  9. }

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

  1. var slothBear = new Bear(“gray”, 10, “sloth”, “India”);
  2. 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.

Accessing Properties of an Object

Properties of an object can be accessed using dot notation.

  1. var myBear = new Bear(“black”, 10, “ursus”, “North America”);
  2. var color = myBear.color; // Gets the color of the bear
  3. 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.

  1. var myObj = {“first name”: “Aneesh”, age: “45”};
  2. var firstName = myObj[“first name”]; // Returns ‘Aneesh’

Bracket notations are also useful when properties names are known only at run-time.

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.

  1. var myObj = {name: “Harsha”, age: 28};
  2. delete myObj.age;

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.
  1. var myObj = {};
  2. var myOtherObj = myObj;

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

That’s all for now.  Leave your comments if you have any questions or suggestions.

Please follow and like us:

There are 0 comments

Leave a Reply

Your email address will not be published. Required fields are marked *