How to create objects in JavaScript

Coming from a background of languages like Java and C/C++, I’ve never really understood  JavaScript. The notion of the language where you can write almost anything and it will not complain (until it breaks in runtime) never made any sense to me. And the fact that JavaScript got to the point where it is today is also a mystery to me. However, JavaScript is here to stay, and there is certainly something I’m missing about the language, so I will try to delve deeper into the language and try to figure it out. I will keep track of my findings in the series of blog posts. So, let’s get started.

Note: For running code samples, you will need JavaScript Engine, like Node.js. Complete source code for all samples in this post can be found at Github.

First steps with objects

In most statically types languages, all objects you create must be of certain type, which must be defined before object is created. Turns out JavaScript takes different and more liberal approach to object creation:

This code creates object myObject , which contains properties name  and size .  To access object properties, use dot notation ( myObject.name ).

But, this is not all. You can also add new properties, and even functions on the fly:

In this snippet, I add new property called city  to myObject , and I also add a function to it. Yes, it is possible to add function to JavaScript objects on the fly! Function is also invoked using dot notation, but parenthesis must be added (ie. myObject.sayHello()  ).

This all seems extremely weird to a developer who used to static typing, but that is how it works. JavaScript is object-based, rather then object-oriented language. It uses prototypes for definition of objects, and has different philosophy from class-based languages, such as Java. More details about this difference can be found in this MDN page.

Accessing properties

Another way to access properties of an object is using square brackets ([]), like in the snippet bellow:

When we create object2  variable, we create a property with name 2 . As you can see this, perfectly valid in JavaScript. However, if you try to access this property using dot notation, you will get an error. But, using bracket notation, it is possible to access this property. Also, you can use this notation to access any property, just make sure to wrap property name in quotes, like shown in line 5.  You can think of this like object being a map of key-value pairs, where property name is the key.

Related to this, you can also enumerate all the properties of an object and access their values:

This will print name and value of each property in myObject .

Creating object with constructors

The way of creating objects described above is only practical for creating single objects. For creating multiple objects, we can define constructors:

Defining a constructor is as simple as creating a function. By convention, it should start with capital letter. In constructor, we use keyword this  to associate properties and functions to the object. Later, we use new  keyword to instantiate objects by calling a constructor.

When creating object car3 , you may wonder why I pass only one argument to constructor, and why this does not throw an error. Turns out th is perfectly legal in JavaScript, and the property gets default value of undefined . If you ask me, this is one of the annoying parts of JavaScript :-), but I guess we learn to live with it.

Creating objects using Object.create()

Another way of creating objects is using built-in function Object.create() . This approach is useful because it allows you to choose which prototype to use for object creation.

This way of creating objects seems a bit limited, because you can’t specify parameters like when using constructors.

So, which way is the best?

With so many different ways to create object, it might be natural to wonder which is the preferred way? Well, the answer seems to be there IS NO preferred way. Depending on particular situation, you may choose one way or another.

  • use first approach if you need to create one-off objects
  • use constructor approach if you need to create with different parameters
  • use third approach if you need to create object that maybe differ in one or two properties

An interesting discussion about this topic can be found in this Stackoverflow question.

 

One thought on “How to create objects in JavaScript

Leave a Reply

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