JavaScript 101:the Object

While the web is advancing to a more interactive sites and more desktop-like web applications, the language(for browser-side programming) hasn`t changed from the early days of web 1.0,it`s still JavaScript the difference is that JavaScript is now treated as a first class language(some people say it is the most used language in the world) and not as a script language to show/hide a div or do some basic client validation.

Even so,most of the JavaScript code laying around is still badly written,misunderstanding of the key concepts of the language is one of the most common mistakes done by amateur JavaScript coders.

One of the basics concepts of JavaScript is that everything is a object,this concept is obvious for those who have used Object Oriented languages before,but the difference between most OO-based languages to JavaScript,is what a object is.

In most languages a object,is a container of other objects be it:functions,integers,strings or any other objects,in those languages,to access a property of a object you use a dot. so: myObj.myProp = 1;

Can be read as:"set myProp of myObj to 1",this also works in JavaScript,but the difference is that in JavaScript you can access it also with this syntax: myObj["myProp"] = 1;

This difference doesn`t seem to be alot but this enable alot of cool stuff.

For start this allow to use a Object as a Hashtable(in C#/Java,dict in Python).
for example: var myObj = {};//this is equal to var myObj = new Object() myObj["test"] = 1; alert(myObj["test"]); this will alert 1.

All this means,that you can access any object in JavaScript like it was a Hashtable.
This enable other powerful stuff that would require using something like Reflection(in languages such as C#).
For example,if i would like to write a function that check if some object have a property: function isDefined(obj,prop) { return obj[prop] != undefined; } myObj = {}; myObj.test = 2; alert(isDefined(myObj,"test")); alert(isDefined(myObj,"test2")); In the first alert it will alert true,while in the other it will alert false.
This is only a really simple case of treating JavaScript objects as Hashtables.

This special thing of the Object can also misused,for example i saw in alot of places that people use arrays as Hashtable,while it works it is wrong,the fact that it works come from the fact that in JavaScript everything is a object and by that definition the Array inherit that behavior from Object.
This means that you could(but don`t use it as it is wrong) a RegExp(Regular Expression) instead,and it would still work.
like this: myObj = new RegExp(); myObj["test"] = 2; alert(myObj["test"]); this will still alert 2,but it is wrong since we are using a RegExp for something that is totally not related,also we are using more memory by using a RegExp over a object.

i hope this help you understand how objects work in JavaScript.

Leave a comment