- Feature Articles
- CodeSOD
- Error'd
-
Forums
-
Other Articles
- Random Article
- Other Series
- Alex's Soapbox
- Announcements
- Best of…
- Best of Email
- Best of the Sidebar
- Bring Your Own Code
- Coded Smorgasbord
- Mandatory Fun Day
- Off Topic
- Representative Line
- News Roundup
- Editor's Soapbox
- Software on the Rocks
- Souvenir Potpourri
- Sponsor Post
- Tales from the Interview
- The Daily WTF: Live
- Virtudyne
Edit Admin
Or if you're using a sane language, use the builtin
joinfunction.Edit Admin
Above all, this!
Addendum 2026-02-18 07:36: And, curiously, despite all its many insanities, JS is sufficiently sane in this particular respect. Well, unless I've missed something about
Array.prototype.join()Admin
I have seen a lot of code where they always append the separator comma, and after the loop they take a substring of the result with all characters except the last. What they usually forget is the case when the array is empty and the for-loop is skipped. There it always crashes badly when taking the substring.
Another way of doing it:
Admin
oh well, the newline did not work. And I can't correct my pevious post... Trying with two slashes instead of backslashes ... Another way of doing it: // let arrayString = '{'; // let separator = "";// for(let i = 0; i < jsArray.length; i++) { // arrayString += separator + jsArray[i];// separator=",";// }// arrayString += '}';//
Edit Admin
Yeah, that's how I do it.
Edit Admin
''' use three single quotes the line breaks will work for you it's also monospaced
Addendum 2026-02-18 09:05: Well, that was wrong
Edit Admin
Edit Admin
You could also use a ternary:
But as @Dragnslcr said,
join()is the better way, and as @Steve_The_Cynic mentioned, JavaScript has it built-in:Edit Admin
I'll also post the periodic reminder that the comments here now render Markdown, so you can use that for quotes, code, etc.