JavaScript is my favorite development language, although I fully realize that it has a lot of limitations. I just discovered one today that I hadn’t thought about since college: passing a variable by reference rather than making a copy of it. Here’s the gist of it, for those who don’t know what I’m talking about.
Take this code, in which we declare and populate a small array:
var lines = [];
lines.push("line 1");
lines.push("line 2");
That works fine, but if you try to pass the lines array to another function, it will make a copy of the array rather than allowing the other function to edit the original array directly. You can set up this other function to return a different array and re-set the original array, but there are times when it would be much easier if you just pass a reference to the original array rather than make a copy of it.
In C, these are called pointers. I don’t know what they’re called in other languages because I haven’t done them in other languages.
Anyway, there are no pointers in JavaScript. So how do we get around this? Well, we could do it the hard way and declare global variables. If you leave the “var” off when referencing a variable for the first time in JavaScript, the variable is global and is accessible from any code on the page. Using global variables can quickly get messy, though, and is generally considered sloppy coding—especially if you’re going back and adding new code and functions all the time like I am with most of my projects.
There is a better solution. JavaScript objects, by default, behave like pointers. The best part is, you can make a variable an object without changing how you reference that variable syntactically. Check it out:
var lines = Object([]);
lines.push("line 1");
lines.push("line 2");
All we’ve changed is that first line, but the variable will now be passed to other functions as a reference to the original array. The variable is invisible outside of the original function and any functions we pass it to.