How can I improve my code which dynamically populates a section of a page?
If you don't need the data as JSON, you could just have the server send you the table markup. Then just inject it straight into the page using .load()

Alternatively, if you want JSON data, or can't/won't mess with the server side, you might consider having a hidden, empty table in the markup to begin with, so you don't need to create the entire thing from scratch. Then you can just populate the header cells with the relevant text, and only worry about adding the rows to tbody.

Of course, it'll introduce tighter coupling between the markup and the JS, which you might want to avoid. Since this is a new project that's probably changing all the time, it might be best to simply stick with you current approach of doing everything in JS, to keep things flexible. But my thinking is that since you're basically hardcoding things like the table headers in JavaScript, you're better off hardcoding it the markup where it belongs, rather than generating it.

And you can also make the coupling a little looser, by using some data-* attributes in the "template" table to declare their intended content.

For instance, have this in the page markup

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Name&lt;/th&gt;
      &lt;th&gt;Command&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;

  &lt;tbody&gt;
    &lt;!-- hidden row template --&gt;
    &lt;tr class="template"&gt;
      &lt;td data-property="name"&gt;&lt;/td&gt;
      &lt;td data-property="com"&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;


Then, on the JS-side, do something like:

var tbody    = $("tbody"),
    template = tbody.children(".template").removeClass(".template").remove(), // removed, but still in memory
    newRow, item;

for(var i = 0, l = deviceArray.commands.length ; i &lt; l ; i++) {
  item   = deviceArray.commands[i];
  newRow = template.clone();
  newRow.children("[data-property]").each(function () {
    var cell = $(this),
        prop = cell.data("property");
    cell.text(item[prop]);
  });
  newRow.appendTo(tbody);
}


That should populate table nicely.

Of course, for such a simple two-column table, it might be overkill. Still, if you need to populate more tables like this, you can create a pretty generic function that you just pass a "scaffold" element like the empty table above plus a data array, and use that anywhere it's needed.