It is no real surprise that one of the primary purposes of computer languages is processing lists (indeed, one of the oldest programming languages – Lisp – is a contraction of the term “list processing”). In Javascript, lists are managed with the Array object. The last few years has seen a significant beefing up of what JavaScript arrays can do as part of the EcmaScript 6 development, to the extent that even many programmers aren’t aware of the full capabilities that arrays offer.

Explore JavaScript Courses

The following is a mixed bag of tricks and methods, focusing both on some of the cooler ES6 code, some on the more esoteric functional programming tricks of ES5. One thing that both of these improvements do is to establish a unifying principle for iterating through lists of items, a problem that’s emerged from twenty years of different people implementing what was familiar to them in JavaScript. That’s admittedly a testimony to how flexible Javascript is.

Avoiding the Index

The traditional way of iterating over an array has been to use indexes, such as the following (Method 1).

Method 1. Using index to iterate over an array

The problem with this is that it first requires the declaration and creation of an index variable, and you still have to resolve the value that the array has at that index. It’s also just aesthetically unpleasing – the emphasis is on the index, not the value.

ES6 introduces the of keyword, which lets you iterate to retrieve an object directly (Method 2)

Method 2. Using the of keyword to iterate over a JavaScript array.

The use of this construction is both shorter and with a much clearer intent, retrieving each color from the list without having to resolve an array position. The use of the const keyword also provides a bit of optimization – by declaring the variable color as constant, JavaScript can reduce the number of pointer resolutions because a new variable isn’t declared each time.

If you’ve ever had to process web pages to retrieve specific elements, you likely also know that the result of functions such as document.getElementsByClassName() is array-like, but not strictly an array. (You have to use the item() keyword on the resulting object instead). The ES6 from () function is a static function of the Array object that lets you convert such objects into JavaScript arrays (Method 3).

Method 3. Converting an array-like object into a JavaScript array.

By the way, how do you know that colorNodes is an array? You use the static Array.isArray() function (Method 4):

Method 4. Testing for an array.

Array-like objects, on the other hand, will self- identify (using the typeof keyword) as objects, or will return false to the .isArray() function. In most cases, so long as an interface exposes the length property, it should be possible to convert it into an array. This can be used to turn a string into an array of characters with a single call (Method 5). Note that Array.from(str) is functionally equivalent to str.split(“”), though possibly not as fast.

Method 5. Inverting a string

In this example, the strReverse() function using from() to convert a string into an array of characters, then uses the Array reverse() function to reverse the order, followed by the join(“”) function to convert the array back into a string.

Prepositional Soup: From In to Of

The of keyword is easy to confuse with the in keyword, though they do different things. The of statement, when applied to an array, returns the items of that array in the order of that array (Method 6).

Method 6. The on keyword returns the values of a JavaScript array.

The in keyword, on the other hand, returns the index keys of the array.

Method 7. The in keyword returns the keys or indices of a JavaScript array.

Note that Javascript arrays, unlike Java arrays, can be sparse. This means that you can have an element a[0] and a[5] without having an a[1] through a[4]. Iterating over the length of an array in this case can cause problems as the length of the Array does not necessarily correspond to the last item in that array (listing 8).

Method 8. Sparse arrays can give problems for iterated indexes, while in provides better support.

The Joy of Higher Order Functions with JavaScript Arrays

Callbacks have become an indispensable part of Javascript, especially with the popularity of jQuery and related browser frameworks and the node.js server. In a callback, a function is passed as an object to another function. Sometimes these callbacks are invoked by asynchronous operations (such as those used to make asynchronous calls to databases or web services), but they can also be passed to a plethora of Array related iteration functions.

Perhaps the simplest of such callbacks is that used by forEach(). The principle argument is the function to be invoked, passing as parameters both an object and its associated key or index:

Method 9. Invoking a function using the forEach() function.

The forEach() function, while perhaps the most commonly known of the “functional” Array functions, is intended primarily to execute an expression without providing a resulting output. If, on the other hand, you want to chain functions together, a more useful Array function is the map() function, which takes the output of each function and adds it to a new array. For instance, the following function (Method 10), takes an array of lower case characters and returns an array where the first letter of each word has been capitalized.

Method 10. Using the map() function.

Note that this function can be extended to turn a sentence into “title case” where every word is capitalized (listing 11).

Method 11. Using array functions to capitalize expressions.

As should be obvious, the split() and join() functions bridge the gap between strings and arrays, where split converts a string into an array using a separator expression, and join() takes an array and joins the strings within the array back together, with a given separator.

What’s even cooler about split() is that it can also be used with regular expressions. A common situation that arises with input data is that you may have multiple spaces between words, and you want to remove all but a single space. You can use split and join (listing 12), to do precisely that.

Explore JavaScript Courses

Method 12. Using arrays to clean up “dirty” text.

While touching on dirty data, another useful “functional” Array function is the filter() function, which will iterate over an array and compare the item against a particular expression. If the expression is true, then the filter() function will pass this along, while if it’s false, nothing gets past. If you have data coming from a database, certain field values may have the value null. Getting rid of these (or some similar “marker” value) can go a long way towards making that data more usable without hiccups (Method 13).

Method 13. Filter cleans up dirty data.

This notation is pretty typical of Javascript – powerful but confusingly opaque with all of these callback functions. However, it turns out that there are some new notational forms in ES6 that can make these kinds of functions easier to read. The predicate construct

can be used to make small anonymous functions. Thus,

Is the same as

With this capability, you can write Method 13 as:

You can even use this notation to create named functions (Method 14).

Method 14. Using predicate notation to define named functions for filters.

You can also go one step further and just say:

Counter tof filter() is find() , which returns the first item (not all items) where the predicate is true. For instance, suppose that you wanted to find from an array the first value that is greater a given threshold. The find() function can do exactly that (Method 15).

Method 15. Use find to get the first item that satisfies a predicate.

Note that if you wanted to get all items where this condition is true then simply use a filter (Method 16).

Method 16. Find retrieves the first value satisfying a predicte, filter, retrieves all of them.

The findIndex() function is related, except that it returns the location of the first match, or -1 if nothing satisfies the predicate.

Did you know that JavaScript Arrays can do map/reduce? This particular process, made famous by Hadoop, involves a two-step process where a dataset (an array) is initially mapped to another “processed” array. This array is then passed to a reducer function, which takes the array and converts it into a single processed entity. You can see this in action in Method 17, which simply sums up the array values, but shows each of the arguments in the process:

Method 17. The reduce() function takes an array and processes content into an accumulator.

The first column shows that result of adding the current value to the accumulator (initially set to initializer, the 0 value given as the second argument of the reduce() function), the second column gives the current value itself, the third item is the index, and the final item is the array.  

A perhaps more realistic example would be a situation where a tax of 6% is added to each cost, but only for values above $10. Again, you can use predicate maps to simplify things (Method 18).

Method 18. Using the reduce() function to calculate a total with a complex tax.

The .toLocaleString() function is very useful for formatting output to a given linguistic locale, especially for currency. If the argument value “de” is passed to the function, the output would be given as “131,52”, where the comma is used as the decimal delimiter and the period is used for the thousands delimiter.

How Do Your Arrays Stack Up?

When I was in college, cafeterias made use of special boxes that had springs mounted in the bottom and a flat plate on which you could put quite a number of trays. The weight of each tray pushed the spring down just enough to keep the stack of trays level, and when you took a tray off, it rose so that the last tray placed on the stack was always the first tray off. This structure inspired programmer who discovered that there were any number of situations where you might want to save the partial state of something by pushing it down on an array, then when you were done processing, popping the previous item back off. Not surprisingly, such arrays became known as, well, stacks.

JavaScript defines four functions – push(), pop(), shift(), and unshift() respectively. Push() places an item on the end of an array, pop() removes and returns it. You can see this in Method 19.

Method 19. Pushing and popping the stack.

Stack based arrays have a number of uses, but before digging into them, you can extend the Array() functionality with a new function called peek() that will let you retrieve the last item in the array (which is the top of the stack), as shown in Method 20.

Method 20. Peeking at the stack.

(Note that you can always get the first items in an array with arr[0]).

One of the more common use for stacks is to maintain a “browse” history in a Javascript application. For instance, suppose that you have a data application where render(id) will draw a “page” of content without doing a server-side reload. Method 21 shows a simple application that keeps a stack which will let you add new items as you continue browsing the stack, but also lets you back up to previously visited “pages”.

Method 21. Creating a stack that remembers color states.

When you select an item from the <select> box, it changes the background to the new color, but then pushes the old color onto the stack (shown as the comma separated list). When you pop the item, the stack removes the last item and makes that the active color.  This is very similar to the way that a web browser retains its internal history.



Contemporary Javascript arrays are far more powerful than they have been in the past.  They provide a foundation for higher order manipulation of functions, let you do filtering and searching, and can even turn complex functions (often ones that relied heavily upon recursion) into chained map/reduce operations. This should make arrays and array functions a staple for both text processing and data analysis. Learning how to work with arrays properly can give you a distinct advantage as a Javascript programmer.

Explore JavaScript Courses

One final note: While ES6 is rapidly making its way into most contemporary browsers and environments such as node.js, they may not necessarily be available in older browsers (especially constructs like of and predicates). There are a number of polyfill libraries that will let you get close, most notably the Babel polfill (http://babeljs.io).

Kurt Cagle is the founder and chief ontologist for Semantical, LLC, a smart data company. He has been working with Javascript since 1996.