How to turn an array into a string

JavaScript polyfill, by , Sunday, March 9th, 2014

This is in most cases extremely easy in JavaScript, as arrays comes with a build in method for that, which is called toString(), and works like this;

  1. var arr = ['left', 'right', 'up', 'down', 'backwards', 'forwards', 'inwards'],
  2. arrStr = arr.toString();
  3.  
  4. // Prints out; "left, right, up, down, backwards, forwards, inwards
  5. console.log(arrStr);

The technique above is nice, but not great. If you have an array and want to make a string out of it, you might want to be able to control the separator between each element, which you cannot with the toString() method. What you then can do is this;

  1. var arr = ['a', 'b', 'c', 'd'],
  2. arrStr = arr.join('~');
  3.  
  4. // Prints out "a~b~c~d"
  5. console.log(arrStr);

This gives you more control and greater possibilities when turning your arrays into strings, and it works for all kinds of values except of object literals. If you apply any of the above to an array of objects, this will happen;

  1. var objArr = [{mango : 'love it', durian : 'cant live without it', avocado : 'gotta have one'}, {one : 1, two : 2, tree : 'wood', four : 4}],
  2. objStr = objArr.toString();
  3.  
  4. // Prints out "[object Object],[object Object]"!!!
  5. console.log(objStr);

This is most likely not what you are looking for, and as mentioned before, it would even happen using join(). Luckily there is help to get. To achieve our goal of turning an array of objects into a string, we turn to JSON for help;

  1. var objArr = [{mango : 'love it', durian : 'cant live without it', avocado : 'gotta have one'}, {one : 1, two : 2, tree : 'wood', four : 4}],
  2. objStr = JSON.stringify(objArr);
  3.  
  4. // Prints out "[{mango : 'love it', durian : 'cant live without it', avocado : 'gotta have one'}, {one : 1, two : 2, tree : 'wood', four : 4}]"
  5. console.log(objStr);

One thing to notice though is, that JSON.stringify() does not work with functions, in which case null will be printed out in the space where you would expect the function.