• (nodebb)

    Also, little pro-tip for generating comma separated code, and this is just a real tiny optimization: before the loop append item zero, start the loop with item 1, and then you can unconditionally prepend a comma, removing any conditional logic from your loop.

    Or if you're using a sane language, use the builtin join function.

  • (nodebb) in reply to Dragnslcr

    Or if you're using a sane language, use the builtin join function.

    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()

  • CodeRefactorer (unregistered)

    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:

    let arrayString = '{';
    let separator = "";
      for(let i = 0; i < jsArray.length; i++) {
        arrayString += separator + jsArray[i];
        separator=",";
        }
      }
      arrayString += '}';
    
  • CodeRefactorer (unregistered)

    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 += '}';//

  • (nodebb)

    separator=",";

    Yeah, that's how I do it.

  • (nodebb) in reply to CodeRefactorer

    ''' 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

  • (nodebb) in reply to CodeRefactorer
    typing three backquotes
    the line breaks will work for you
    it's also monospaced
    
  • (nodebb) in reply to CodeRefactorer

    You could also use a ternary:

    let arrayString = '{';
    for(let i = 0; i < jsArray.length; i++) {
      arrayString += (i ? ',' : '') + jsArray[i];
    }
    arrayString += '}';
    

    But as @Dragnslcr said, join() is the better way, and as @Steve_The_Cynic mentioned, JavaScript has it built-in:

    let arrayString = '{' + jsArray.join(',') + '}';
    
  • (nodebb)

    I'll also post the periodic reminder that the comments here now render Markdown, so you can use that for quotes, code, etc.

Leave a comment on “Contains Some Bad Choices”

Log In or post as a guest

Replying to comment #691462:

« Return to Article