Q:

Output Javascript array into HTML with better readability

I'm trying to output the data in an array (produced by this code) to a div in a simple web page, using this jquery:
$('#submit').click(function(e) {
        e.preventDefault();    
        var num = $('#userInput').val();       
        var primes = sieve(num);          // sieve() produces array of prime numbers
        console.log(primes);          
        $('#answer').html(primes);
    });

The console is logging the array as I would like to see it, (i.e. 2, 3, 5, 7, 11, 13, etc.) but the content in #answer is displaying without any formatting (23571113 etc.).
How can I get the data to display in a more readable format? I've tried using .split and .join to add commas or line breaks but no joy...

A:

Just join the array into a string using whatever separator you want to use. Also, when filling in text that isn't HTML, don't use html, use text:
$('#answer').text(primes.join(", "));

You (and lurkers) may be wondering why you didn't get the default Array#toString behavior, which is to do .join() (where join defaults to the separator ","). The reason is that the html function is appending each element of the array to the target element individually, as a new text node, instead of calling toString on the array. (This doesn't appear to be documented behavior.) Surprising, but true:

var answer = $("#answer");
answer.html([1, 2, 3, 4, 5]);
console.log(answer[0].childNodes.length); // 5
<div id="answer"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

text applies toString, but the default separator used (",", no space after ,) probably isn't what you want:

var answer = $("#answer");
answer.text([1, 2, 3, 4, 5]);
console.log(answer[0].childNodes.length); // 5
<div id="answer"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

