9 JavaScript Tips You May Not Know
JavaScript is a fully-featured Object-Oriented programming language. On the surface, it shares syntactical similarities with Java and C, but the mentality is quite different. At its core, JavaScript is more similar to functional languages. Inside is a list of JavaScript tips, some offer techniques to simulate features found in C-like languages (such as assertions or static variables). Others are meant to improve performance and explore some of the more obscure parts of the web scripting language.
Arrays as Multipurpose Data Structures
Although that JavaScript may seem limited on the data structure front at first glance, its Array class is much more versatile than the usual array type found in other programming languages (like C++ or Java). It's commonly used as an array or associative array, and this tip demonstrates how to use it as a stack, queue, and binary tree. Re-using the Array class instead of writing such data structures provides two benefits: First, time isn't wasted rewriting existing functionality, and second, the built-in browser implementation will be more efficient than its JavaScript counterpart.
Stack
A stack follows the Last-In First-Out (LIFO) paradigm: an item added last will be removed first. The Array class has 2 methods that provide stack functionality. they are push() and pop(). push() appends an item to the end of the array, and pop() removes and returns the last item in the array. The next code block demonstrates how to utilize each of them:
var stack = []; stack.push(2); // stack is now [2] stack.push(5); // stack is now [2, 5] var i = stack.pop(); // stack is now [2] alert(i); // displays 5
Queue
A queue follows the First-In First-Out (FIFO) paradigm: the first item added will be the first item removed. An array can be turned into a queue by using the push() and shift() methods. push() inserts the passed argument at the end of the array, and shift() removes and returns the first item. let's see how to use them:
var queue = []; queue.push(2); // queue is now [2] queue.push(5); // queue is now [2, 5] var i = queue.shift(); // queue is now [5] alert(i); // displays 2
It's worth noting that Array also has a function named unshift(). This function adds the passed item to the beginning of an array. So a stack can also be simulated by using unshift()/shift(), and a queue can be simulated by using unshift()/pop().
If all these function names are confusing, you may create aliases with your own names. For example, to create a queue with methods named add and remove:
var queue = []; queue.add = queue.push; queue.remove = queue.shift; queue.add(1); var i = queue.remove(); alert(i);
Binary Tree
A binary tree represents data in a tree of nodes. Each node has a value and two children (left and right). In C, this data structure is usually implemented using structures and pointers. This implementation is possible to do in JavaScript using objects and references; however, for smaller trees, there is an easier and quicker way using only one array. The first item of the array will be the head of the tree. Indexes of left and right child nodes if node i can be calculated using the following formula:
leftChild(i) = 2i + 1 rightChild(i) = 2i + 2
This image illustrates the method (courtesy of Wikipedia):

As you see, this method isn't exclusive to JavaScript, but it can be very useful when dealing with small trees. You can, for example, write your own helper functions for getting and setting a node's value or children, and traversing the tree, and those methods will be as simple as doing arithmetic calculations and/or for loops. On the other hand, the disadvantage of this method is that wasted space grows as the depth of the tree increases.
String Concatenation vs. Array.join
This cannot be stressed enough, doing many string concatenation operations can be a major hit on performance, and it's easy to avoid in many situations. Consider for example that you want to build a string out of many pieces, one bad way to do this is using the + to concatenate all pieces into a huge string, one piece at a time:
str = ''; for (/* each piece */) { str += piece; // bad for performance! } return str;
This method will result in too many intermediate strings and concatenation operations, and will poorly perform overall.
A better approach to this problem is using Array.join(), this method joins all array elements into one string:
var tmp = []; for (/* each piece */) { tmp.push(piece); } str = tmp.join(''); // Specified an empty separator, thanks Jonathan return str;
This method doesn't suffer from the extra string objects, and generally executes faster.
Binding Methods To Objects
Anyone who works with JavaScript events may have come across a situation in which they need to assign an object's method to an event handler. The problem here is that event handlers are called in the context of their HTML element, even if they were originally bound to another object. To overcome this, I use a function that binds a method to an object; it takes an object and method, and returns a function that always calls the method in the context of that object. I found the trick in Prototype, and wrote the following function to use it in projects that don't include Prototype:
function bind(obj, method) { return function() { return method.apply(obj, arguments); } }
And this snippet shows how to use the function:
var obj = { msg: 'Name is', buildMessage: function (name) { return this.msg + ' ' + name; } } alert(obj.buildMessage('John')); // displays: Name is John f = obj.buildMessage; alert(f('Smith')); // displays: undefined Smith g = bind(obj, obj.buildMessage); alert(g('Smith')); // displays: Name is Smith
Sorting With a Custom Comparison Function
Sorting is a common task. JavaScript provides a method for sorting arrays. However, the method sorts in alphabetical order by default. Non-string elements are converted to strings before sorting, which leads to unexpected results when working with numbers:
var list = [5, 10, 2, 1]; list.sort() // list is now: [1, 10, 2, 5]
The explanation of this behavior is simple: Numbers are converted to strings before sorting them, so 10 becomes '10' and 2 becomes '2'. The JavaScript interpreter compares two strings by comparing the first two characters of each: str1 is considered "less than" str2 if str1's first character comes before str2's first character in the character set. In our case, '1' comes before '2' so '10' is less than '2'.
Fortunately, JavaScript provides a way to override this behavior by letting us supply a comparison function. This function defines how elements are sorted, it takes two compared elements a and b as parameters, and should return:
- A value less than zero if a < b.
- zero if a == b.
- A value greater than zero if a > b.
Programming such a function for number comparison is trivial:
function cmp(a, b) { return a - b; }
Now we can sort our array using this function:
var list = [5, 10, 2, 1]; list.sort(cmp); // list is now: [1, 2, 5, 10]
This flexibility in Array.sort() allows for more sophisticated sorting. Let's say you have an array of forum posts, each post looks something like:
var post = { id: 1, author: '...', title: '...', body: '...' }
If you want to sort the array by post id's, create the following comparison function:
function postCmp(a, b) { return a.id - b.id; }
It's reasonable to say that sorting using a native browser method is going to be more efficient than implementing a sort function in JavaScript. Of course, data should be sorted server-side if possible, so this shouldn't be used unless absolutely necessary (for example, when you want to offer more than one sort order on one page, and do the sorting in JavaScript).
Assertion
Assertion is one of the commonly-used debugging techniques. It's used to ensure that an expression evaluates to true during execution. if the expression evaluates to false, this indicates a possible bug in code. JavaScript lacks a built-in assert function, but fortunately it's easy to write one. The following implementation throws an exception of type AssertException if the passed expression evaluates to false:
function AssertException(message) { this.message = message; } AssertException.prototype.toString = function () { return 'AssertException: ' + this.message; } function assert(exp, message) { if (!exp) { throw new AssertException(message); } }
Throwing an exception on its own isn't very useful, but when combined with a helpful error message or a debugging tool, you can detect the problematic assertion. You may also check whether an exception is an assertion exception by using the following snippet:
try { // ... } catch (e) { if (e instanceof AssertException) { // ... } }
This function can be used in a way similar to C or Java:
assert(obj != null, 'Object is null');
If obj happens to be null, the following message will be printed in the JavaScript console in Firefox:
uncaught exception: AssertException: Object is null
Static Local Variables
Some languages like C++ support the concept of static variables; they are local variables that retain their values between function calls. JavaScript doesn't have a static keyword or direct support for this technique. However, the fact that functions are also objects makes simulating this feature possible. The idea is storing the static variable as a property of the function. Suppose that we want to create a counter function, here is a code snippet that shows this technique in action:
function count() { if (typeof count.i == 'undefined') { count.i = 0; } return count.i++; }
When count is called for the first time, count.i is undefined, so the if condition is true and count.i is set to 0. Because we are storing the variable as a property, it's going to retain its value between function calls, thus it can be considered a static variable.
We can introduce a slight performance improvement to the above function by removing that if check and initialize count.i after defining the function:
function count() { return count.i++; } count.i = 0;
While the first example encapsulates all of count's logic in its body, the second example is more efficient. The choice is up to you.
null, undefined, and delete
JavaScript is difference from other programming languages by having both undefined and null values, which may cause confusion for newcomers. null is a special value that means "no value". null is usually thought of as a special object because typeof null returns 'object'.
On the other hand, undefined means that the variable has not been declared, or has been declared but not given a value yet. Both of the following snippets display 'undefined':
// i is not declared anywhere in code alert(typeof i);
var i; alert(typeof i);
Although that null and undefined are two different types, the == (equality) operator considers them equal, but the === (identity) operator doesn't.
JavaScript also has a delete operator that "undefines" an object a property (thanks zproxy), it can be handy in certain situations, you can apply it to object properties and array members, variables declared with var cannot be deleted, but implicitly declared variables can be:
var obj = { val: 'Some string' } alert(obj.val); // displays 'Some string' delete obj.val; alert(obj.val); // displays 'undefined'
Deep Nesting of Objects
If you need to do multiple operations on a deeply nested object, it's better to store a reference to it in a temporary variable instead of dereferencing it each time. For example, suppose that you want to do a series of operations on a textfield accessible by the following construct:
document.forms[0].elements[0]
It's recommended that you store a reference to the textfield in a variable, and use this variable instead of the above construct:
var field = document.forms[0].elements[0]; // Use field in loop
Each dot results in an operation to retrieve a property, in a loop, these operations do add up, so it's better to do it once, store the object in a variable, and re-use it.
Using FireBug
Firefox has a fabulous extension for debugging JavaScript code called FireBug. It offers an object inspector, a debugger with breakpoints and stack views, and a JavaScript console. It can also monitor Ajax requests. Moreover, the extension provides a set of JavaScript functions and objects to simplify debugging. You may explore them in detail at FireBug's documentation page. Here are some that I find most useful:
$ and $$
Those familiar with Prototype will immediately recognize these two functions.
$() takes a string parameter and returns the DOM element whose id is the passed string.
$('nav') // returns the element whose id is #nav.
$$() returns an array of DOM elements that satisfy the passed CSS selector.
$$('div li.menu') // returns an array of li elements that are // located inside a div and has the .menu class
console.log(format, obj1, ...)
The console object provides methods for displaying log messages in the console. It's more flexible than calling alert. The console.log() method is similar to C's printf. It takes a formatting string and optional additional parameters, and outputs the formatted string to the console:
var i = 1; console.log('i value is %d', i); // prints: // i value is 3
console.trace()
This method prints a stack trace where it's called. It doesn't have any parameters.
inspect(obj)
This function takes one parameter. It switches to the inspection tab and inspects the passed object.











zproxy (not verified) | instead of using console one | Sun, 2006/10/08 - 10:02am
instead of using console one can use firefox
window.dump(<string>)method.also delete is for removing a member of a type.
you can also do
<expr> = void(0), which also sets a variable to undefined state.I did not understand the binary tree section. maybe you can clarify.
cheers
Ayman | Hi,Thanks for your | Sun, 2006/10/08 - 5:58pm
Hi,
Thanks for your feedback, regarding delete, while I did mention that it removes properties, the opening sentence is ambiguous, I've correct it, thanks.
As for binary trees, I'll try to clarify the concept briefly, suppose that you have the following tree:
a/ \
b c
/ \
d e
ais the head of the tree, therefore, we will store it at the beginning of the array:[a]bandcare children ofa, anda's index is 0, according to the formulas I posted:Index of a's left child = 2 * (a's index) + 1 = 2 * 0 + 1 = 1So
bwill be stored at index 1. Forc, we will do the same thing, but use the right child formula:Index of a's right child = 2 * (a's index) + 2 = 2 * 0 + 2 = 2Our array now looks like:
[a, b, c]Now let's see where to store
c's children:Index of c's left child = 2 * (c's index) + 1 = 2 * 2 + 1 = 5Index of c's right child = 2 * (c's index) + 2 = 2 * 2 + 2 = 6
And the array becomes:
[a, b, c, 'undefined', 'undefined', d, e]Notice how there are 2 undefined positions in the array, if
bhad children, they would be stored there.Hope this clears things up.
Anonymous (not verified) | You have opened my eyes | Sun, 2006/10/08 - 7:59pm
Hi:
These is great information you are sharing.
Thanks,
Anonymous (not verified) | Good info, thanks! | Sun, 2006/10/08 - 8:25pm
Good info, thanks!
Anonymous (not verified) | Excellent tips and a very | Sun, 2006/10/08 - 10:30pm
Excellent tips and a very useful website! Dugg and submitted this article at howtohut http://www.howtohut.com/9_javascript_tips_you_may_not_know
Mike Atlas (not verified) | first class functions | Mon, 2006/10/09 - 1:14am
You neglected one of the most fundamentally important things about JavaScript that most people do not know:
It treats functions as first class values.
In other words, you can do great things like this in JavaScript:
var averageOfTwo = function(x,y) {return (x+y)/2;
}
alert( averageOfTwo(1,3) );
Ayman | I didn't neglect it, I | Mon, 2006/10/09 - 2:41am
I didn't neglect it, I assumed that the reader is aware of this feature, it's used in tip #1 when creating a synonym for push, and #3 in which the returned bound function is an anonymous function.
Anonymous (not verified) | That is not an example of | Tue, 2008/08/19 - 5:53pm
That is not an example of first-class functions, anyway: you're just calling the
alert()function with the result of evaluating theaverageOfTwo(1, 3)function. Any reasonable language supports that; what is slightly less common is the ability to treat functions as first-class values.Anonymous (not verified) | very userful | Mon, 2006/10/09 - 1:24am
it's very userful,thks
Alok (not verified) | This is a real good and | Mon, 2006/10/09 - 3:50am
This is a real good and informative article. I have started working in javascript for last few months. I am getting more and more impressed by its little tricks and dynamicity of the language.
Awesome work. Thanks
leo (not verified) | counter example | Mon, 2006/10/09 - 5:56am
For the counter example, an immediate function application returning a function is a common and clear pattern when constructing functions with local state:
functionFoo = (function () { var counter = 0; return function () { return counter++; }; })();
Two syntactic forms I would mention are:
1. functional if: ? :
Instead of
var x;
if (test) { x = branch1; } else { x = branch2; }
do
var x = test ? branch1 : branch2;
2. sequencing: (*)
when not using the above function application with a stateful function return, a light version would be something like
someFunction((y+=4, x+=y), z) being shorthand for
y+=4
x+=y
someFunction(x,z)
- Leo
- Leo
Anonymous (not verified) | Useful... | Mon, 2006/10/09 - 12:02pm
Useful info, thanks!
Tim (not verified) | that custom sort function is sooo useful | Mon, 2006/10/09 - 1:30pm
THANKS for the custom sort function, it's sooo useful ! thanks !
rsr (not verified) | javascript | Mon, 2006/10/09 - 5:55pm
May I know if javascript can read and write to a local disc file?
Ayman | In short no, JavaScript is | Mon, 2006/10/09 - 7:08pm
In short no, JavaScript is not allowed to read or write to local file system for security reasons. Use cookies for local storage.
However, some browsers allow sufficiently privileged scripts to access local file system, for example, Mozilla browsers allow installed extensions to access local files, check this page for some code samples.
Anonymous (not verified) | Delimiters | Mon, 2006/10/09 - 10:54pm
Just to niggle, the default statement separator in English is a period, not a comma. I have taken the liberty of rewriting the first paragraph below item 6:
Some languages like C++ support the concept of static variables. These are local variables that retain their values between function calls. JavaScript doesn't have a static keyword or direct support for this technique. However, the fact that functions are also objects makes simulating this feature possible. The idea is to store the static variable as a property of the function. Suppose that we want to create a counter function. Here is a code snippet that shows this technique in action:
Ayman | Thanks for the tip. I | Mon, 2006/10/09 - 11:25pm
Thanks for the tip. I noticed that I overuse commas before. Looks like this is a common error called comma splice :)
SAAL (not verified) | Compatibility | Tue, 2006/10/10 - 3:44pm
is everything above compatible with most browsers? I mean, is there anything here olny compatible with curring edge JS processors?
Ayman | Yeah, except for the last | Tue, 2006/10/10 - 7:50pm
Yeah, except for the last one (Firebug, which is obviously Firefox-only), all tips should be compatible with modern browsers (Gecko based, IE 5.5+, KHTML, Opera).
Anonymous (not verified) | Array.push() | Sun, 2006/10/15 - 3:30am
IE5 (or more accurately, JScript 5.0) did not have support for Array.push among a number of other things like the call or apply methods. Also interesting to note is that Microsoft still considers IE5.0 a supported browser (because of the support window for Windows 2000 for which IE5 was the default browser) whereas Microsoft has discontinued support for IE5.5. Somewhat moot as nobody should really be using either of them.
Anonymous (not verified) | Also worthy of note is that | Thu, 2008/08/21 - 11:16pm
Also worthy of note is that one can obtain the updated script engine for their ancient 5.x browser as a separate install.
Jonathan (not verified) | Array.join | Wed, 2006/10/11 - 4:22pm
I tried your Array.join technique for string concatenation, but it adds a comma between every part of the array. Like,this,you,know,what,I,mean?
Jonathan (not verified) | ah I found the answer.. you | Wed, 2006/10/11 - 4:29pm
ah I found the answer.. you need to use var.join("") instead of var.join()
Jonathan (not verified) | I did a little more | Wed, 2006/10/11 - 4:39pm
I did a little more investigation into this, and the technique as described on http://www.comet.co.il/en/articles/performance/article.html is alot faster..
it uses buffer[buffer.length] = "somedata"
instead of buffer.push("somedate")
in my tests it's about 20 times as fast..
Ayman | Interesting! So we have a | Wed, 2006/10/11 - 11:04pm
Interesting observation. What browser(s) did you test with?
Gábor (not verified) | Read the article | Thu, 2006/10/12 - 10:10am
IE 6 and FF 1.5B1
Ayman | Tested with Firefox and | Thu, 2006/10/12 - 5:54pm
Tested with Firefox and looks like
array[array.length] = valis indeed faster thanarray.push(val). Interesting, thanks Jonathan and Gábor!Wes (not verified) | String concat vs array.join | Sun, 2006/10/29 - 3:22am
Tested the following on FF2.0 (Mac G4 1.25 GHz ) and concat was 3x faster. Unless my test is flawed somehow (please tell me!).
function concat() {
var start = new Date().getTime();
var s = "";
for (var i=0; i<2000; i++) {
s+= "string";
}
alert(new Date().getTime() - start); // gives 2 or 3
}
function buffer() {
var start = new Date().getTime();
var s = [];
for (var i=0; i<2000; i++) {
s[i] = "string";
}
var joined = s.join("");
alert(new Date().getTime() - start); // gives 9
}
Wes (not verified) | OK, concat() may cause | Tue, 2006/10/31 - 4:40pm
OK, concat() may cause trouble because it's the name of a String object method, though it shouldn't. Regardless, I tested again on a Windows machine, faster than my Mac, and had to increase the number of iterations to 8000 to get decent results. The results were wildly inconsistent in both FF2 and IE7, but on average using the concat is generally a bit faster in FF, but slower in IE. So I guess it depends which browser you want to optimize for. But how often do you need to build a string that large? And we're talking about differences of milliseconds -- It really makes very little difference practically, as far as I can tell.
function makeString() {
var start = new Date().getTime();
var s = "";
for (var i=0; i<8000; i++) {
s+= "string";
}
alert(new Date().getTime() - start); // faster in FF
}
function buffer() {
var start = new Date().getTime();
var s = [];
for (var i=0; i<8000; i++) {
s[i] = "string";
}
var joined = s.join("");
alert(new Date().getTime() - start); // faster in IE
}
Ayman | Hi, I remember running into | Wed, 2006/11/01 - 6:02pm
Hi,
I remember running into similar results when I conducted my tests. I think that this test doesn't reflect real situations in which one needs to concatenate a large number of strings for two reasons:
s) is not returned or used anywhere in the function. I think that Firefox optimizes away theforloop, which results in great improvements to performance. Try to makesa global variable for example, and see how it goes. If I recall correctly, results changed dramatically in my tests after this modification."string"with"string" + i(For example).Thanks for your feedback, and I hope that my reply sheds some light on the issue.
Post new comment