Oct 21

So, what is an object in JavaScript?–part I

Posted in Javascript      Comments Off on So, what is an object in JavaScript?–part I

After publishing my previous post, I’ve received some questions from friends which make me believe that I probably need to elaborate further on my “what is an object in JavaScript thesis”. So be it. If you’ve read the previous post, you probably remember me writing this:

“In JavaScript, you can think of objects as being containers for key/value pairs.”

Well, it’s not completely wrong, but the truth is that there’s a little more to an object than that and ECMAScript5 has made those little things more visible than ever. So, here’s a better definition of what an object is in JavaScript (taken from the ECMAScript 6 draft):

“An ECMAScript object is a collection of properties each with zero or more attributes that determine how each property can be used—for example, when the Writable attribute for a property is set to false, any attempt by executed ECMAScript code to change the value of the property fails.”

Did you notice the attribute part that is applied to each property? Yes, that’s the part I’ve omitted from my initial definition and that is an important part of how you can create objects from ECMAScript5 onwards. In practice, ECMAScript5 introduces several methods which allow us to influence the way a property is created and we’ll come back to them in a future post.

Notice that properties of an object will always hold other objects which will also have its own properties, primitive values or functions. Currently, ECMAScript defines primitive type as a value of one of the following types: Undefined, Null, Boolean, Number and String. If a value doesn’t belong to one of the previous types, then it is an Object. “What about functions?”, you ask. Well, functions are special types of objects which can be “called” (ie, you can use them with the () operator in order to get a result back). Besides Object and primitive values, the spec introduces several predefined types (aka ECMAScript entities or objects) that we can use in a program (ex: Date, RegExp, etc.) and some predefined operators.

And I’d say that this is a better (though still formal) definition of an object. In the next post, we’ll dig a little deeper and see how the spec “lays” objects in memory.