But the "looseness" of Javascript can also tempt you to fall into programming habits that don't scale well.
When I first started learning Javascript I approached it as a purely function based language. Probably because I was already familiar with SCL (Screen Control Language) in SAS/AF and that's what I likened Javascript to. But anyways, all my JS code looked like this:
function doSomething(someVal) {
var someLocal;
// do some stuff
return rValue;
}
function doSomethingElse(someVal) {
var someLocal;
// do some other stuff
return rValue;
}
And I would store it in a file and include the file as a link in my header tags.
This works perfectly well and so I had no incentive to change it. Until I started getting lots of functions in lots of files. It doesn't scale well. But by changing the coding style just a little bit, I am able to write my JS code so it is much easier to maintain. Using JavaScript Object Notation (or JSON) I can fake namespaces. This lets me take more control over the design of my JS code. Using JSON the above would be rewritten:
myNameSpace = {
doSomething function(someVal) {
var someLocal;
// do some stuff
return rValue;
} ,
doSomethingElse function(someVal) {
var someLocal;
// do some other stuff
return rValue;
}
};
Then when I want to use one of the functions, I just preface it with the object name ( myNameSpace.doSomething(withThis); )
I usually choose the object name to be the same as the name of the javascript file. That way I avoid name collisions, and I can quickly find where a function is defined if I need to look at the source code.
Certainly, this is not a great leap forward in web programming. But I still see so much function-style javascript online that I thought it would be useful to pass it along.