Some of you probably already knew this, but I only recently discovered this (accidentally) while building a wrapper around Postgresql queries in Node, and my mind is blown, to be honest.
Calling toString() on an array will automatically return the values within as a comma-separated string. Best of all, there will be no hanging comma and all whitespace is removed. Implementations based on join
will have a space between the items, toString()
on the array itself will not.
I have always used .join(', ')
to create comma-separated strings from array values, but this is so much nicer.
const arr = [ 'username', 'email', 'firstName', 'lastName', 'password' ]; arr.toString();
There are a million ways you can comma separate an array of values into a string, you can use reduce
, a for
loop, the classic join
method and probably a few others not mentioned. Why overcomplicate?
I have to admit, don’t ever remember seeing a trailing comma from a .join( ) operation, and Mozilla docs don’t describe that in their documentation, either. Need to take a second look when I get time…