array.join

It seems that lately I have been covering prototype functions for arrays that make your life easier, so I figure I need to cover array.join().

Have you ever written something like this to make data in a template look nice:

var arr = [1, 2, 3, 4];
var str = '';
for (var i = 0; i < arr.length; i++) {
    str += arr[i] + ', ';
}

When I was first using JavaScript or when I was using a different language I have done this before. After the first couple of times I realized before I wrote the code that I didn't want the trailing ', ' on the last element. So at first I would do something like:

var arr = [1, 2, 3, 4];
var str = '';
var first = true;
for (var i = 0; i < arr.length; i++) {
    if (first) {
        first = false;
    } else {
        str += ', ';
    }
    str += arr[i];
}

This has some flaws. First, it is far more complex then it needs to be, making it difficult to read. Second, we have to test for the value of first every time.

Obviously I could have made it simpler if I had used i instead of a separate variable are checked if str was empty before adding the ', ' in front of the variable. Whatever the case it still has always felt like it could be a lot simpler. One way to make it simpler is to simply remove the trailing ', ' using string.substring().

var arr = [1, 2, 3, 4];
var str = '';
for (var i = 0; i < arr.length; i++) {
    str += arr[i] + ', ';
}
str = str.substring(0, str.length - 2);

So while this is much simpler it is still more complex than is needed since JavaScript has array.join(). If we were to make use of that it would simplify to:

var arr = [1, 2, 3, 4];
var str = arr.join(', ');

All array.join() does is combine the elements in an array into a string separated by whatever is passed into the function. By default join uses a comma with no spaces, ','.

This is a simple function for a seemingly simple task.

comments powered by Disqus