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):
Binary tree in an array

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.

Tags:
Submitted by Ayman on Wed, 2006/09/27 - 5:26pm

zproxy (not verified) | instead of using console one | Sun, 2006/10/08 - 9: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 - 4: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

a is the head of the tree, therefore, we will store it at the beginning of the array:

[a]

b and c are children of a, and a's index is 0, according to the formulas I posted:

Index of a's left child = 2 * (a's index) + 1 = 2 * 0 + 1 = 1

So b will be stored at index 1. For c, 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 = 2

Our 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 = 5
Index 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 b had children, they would be stored there.

Hope this clears things up.

Anonymous (not verified) | Nice! | Sat, 2009/09/19 - 3:57am

Nice explanation. Just from your explanation, it's easy to derive a binary tree class, complete with manipulation methods (e.g.: add, remove, get, find, etc.). The math is simple and constant.

Thanks
Michael

Anonymous (not verified) | You have opened my eyes | Sun, 2006/10/08 - 6:59pm

Hi:

These is great information you are sharing.

Thanks,

Anonymous (not verified) | Good info, thanks! | Sun, 2006/10/08 - 7:25pm

Good info, thanks!

Anonymous (not verified) | Excellent tips and a very | Sun, 2006/10/08 - 9: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 - 12: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 - 1: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 - 4:53pm

That is not an example of first-class functions, anyway: you're just calling the alert() function with the result of evaluating the averageOfTwo(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 - 12:24am

it's very userful,thks

Alok (not verified) | This is a real good and | Mon, 2006/10/09 - 2: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 - 4: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

_es (not verified) | with | Wed, 2009/01/28 - 5:33am

with({counter:0}) var functionFoo2 = function(){return counter++;};

Anonymous (not verified) | Useful... | Mon, 2006/10/09 - 11:02am

Useful info, thanks!

Tim (not verified) | that custom sort function is sooo useful | Mon, 2006/10/09 - 12:30pm

THANKS for the custom sort function, it's sooo useful ! thanks !

rsr (not verified) | javascript | Mon, 2006/10/09 - 4: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 - 6: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) | Conceptuall incorrect | Sat, 2009/09/19 - 4:07am

It's not that _JavaScript_, per se, is not allowed to read/write to and from the local file system; rather, it's the JavaScript _runtime_engine_ that disallows it. If you wanted to, you could hack Mozilla so as to link extra (non-standard) JS methods to low-level filesystem-handling code. Then you could call a File.open(...) JS method and it would get dispatched internally to custom file-handling methods (presumably C or C++ on most platforms; maybe Obj. C under OS X).

Of course, it would never gain widespread adoption for security reasons.

Michael

Anonymous (not verified) | Delimiters | Mon, 2006/10/09 - 9: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 - 10: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 - 2: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 - 6: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 - 2: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 - 10: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 - 3: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 - 3: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 - 3: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 - 10:04pm

Interesting observation. What browser(s) did you test with?

Gábor (not verified) | Read the article | Thu, 2006/10/12 - 9:10am

IE 6 and FF 1.5B1

Ayman | Tested with Firefox and | Thu, 2006/10/12 - 4:54pm

Tested with Firefox and looks like array[array.length] = val is indeed faster than array.push(val). Interesting, thanks Jonathan and Gábor!

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <strike> <code> <ul> <ol> <li> <blockquote> <sup> <sub> <b> <i> <u>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options

About

Ayman Hourieh

Computer Science graduate, Open Source enthusiast and Software engineer (Site reliability) at Google.

I'm 26 years old, and live in Dublin, Ireland.

This is my personal blog. The views expressed on these pages are mine alone and not those of my employer.

More

Feeds

RSS Feed Twitter

Books

Django 1.0 Website Development

Django 1.0 Website Development
Build powerful web applications, quickly and cleanly, with the Django application framework.

The second edition of my Django book. Published by Packt Publishing in March 2009.

Learning Website Development with Django

Learning Website Development with Django
A beginner's tutorial to building web applications, quickly and cleanly, with the Django application framework.

My first book. Published by Packt Publishing in April 2008.