Arrays as Multipurpose Data Structures
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() 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:
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() 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:
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
shift(), and a queue can be simulated by using
If all these function names are confusing, you may create aliases with your own names. For example, to create a queue with methods named
i can be calculated using the following formula:
This image illustrates the method (courtesy of Wikipedia):
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:
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:
This method doesn’t suffer from the extra string objects, and generally executes faster.
Binding Methods to Objects
And this snippet shows how to use the function:
Sorting With a Custom Comparison Function
- 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:
Now we can sort our array using this function:
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:
If you want to sort the array by post id’s, create the following comparison function:
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:
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:
This function can be used in a way similar to C or Java:
Static Local Variables
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:
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:
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
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
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 are two different types, the == (equality) operator considers them equal, but the === (identity) operator doesn’t.
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:
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:
It’s recommended that you store a reference to the textfield in a variable, and use this variable instead of the above construct:
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.
$ 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.
$$() returns an array of DOM elements that satisfy the passed CSS selector.
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:
This method prints a stack trace where it’s called. It doesn’t have any parameters.
This function takes one parameter. It switches to the inspection tab and inspects the passed object.