Objects in JavaScript (part I)

Thu, 16 Apr 2009

Recently I was talking to friend of mine about objects in JavaScript. He is writing JavaScript for living and very good at it, however I found that he doesn’t understand some core features of the language. So, in case you have this gap in understanding JavaScript, I’ll try to explain.

Friend of mine give cite me one book:

“The interesting thing about ECMAScript primitive values for Booleans, numbers, and strings is that they are pseudo-objects, meaning that they actually have properties and methods.”

I am really sorry, but this doesn’t make any sense.

First lets take a look at this example:

var a = 5;
a.t = 3;
alert(a.t);

It will alert “undefined”. Why? If “a” is a “pseudo-object” then why it doesn’t keep my property? The thing is, “a” is not an object. Not even “pseudo-object”. It is primitive number. It doesn’t have properties. As you know JavaScript convert variable from one type to another on the fly:

var b = "w" + a + [1, 2, 3];

In this example number “a” and array [1, 2, 3] will be converted to string on the fly. The same is happening with anything before “.” operator, JavaScript simply converts left hand side parameter to object. So, at the second line of the example JavaScript creates new object Number with value equals to “a” (5 in our case), then create new property “t” with value 3. But then this object is not assigned back to variable “a”, it is just disappear in garbage. Third line will again create new object and will try to read it property “t”, which is undefined.

Primitive types like boolean, number and strings are not objects, they could be converted to objects. What the rule? JavaScript has six built-in types: null, undefined, number, string, boolean and object. The conversion rule is simple: if input is object, leave it as is; if input is null or undefined, throw an exception; otherwise create new object (new Number(input) or new String(input) or new Boolean(input)). Hope this small bit will help somebody to understand objects in JavaScript a bit better. Next type I write about prototype and friends.