Returning Function Calls from an Array within a JavaScript Function I'd like to use JavaScript to generate HTML.

I've made a JavaScript function object that has two parameters; a string and generic object. The string is used to specify the type of HTML element you want to generate and the generic object is a container for key value pairs specifying the element's attributes -- or a string for simple elements like paragraphs containing only text that needs no id or class specification.

I'm drafted some functions that generate some HTML elements. I then contained the functions in an array that is a local variable of a function called html.

When html is called with appropriate arguments (e.g. html("element", {id:"myElement"})), a string of HTML text is returned.

I wonder what the drawbacks of the approach are. More specifically, is there a better method to achieve the same results?

var html = function (type, spec={}) {
  html_element = [];

  html_element["table"] = function() {
    markup = "&lt;table&gt;";

    if (spec.cols) 
    {
      markup += "&lt;tr&gt;";

      for (value in spec.cols)
        markup += "&lt;th&gt;" + spec.cols[value] + "&lt;/th&gt;";

      markup += "&lt;/tr&gt;";
    }

    while (spec.rows.length)
    {
      markup += "&lt;tr&gt;";

      for (data in (row = spec.rows.shift()))
        markup += "&lt;td&gt;" + row[data] + "&lt;/td&gt;";

      markup += "&lt;/tr&gt;";
    }

    return markup += "&lt;/table&gt;";
  };


  html_element["button"] = function() {
    if (spec.hasOwnProperty("value")) value = spec.value;
    else                              value = "";

    return "&lt;button id=\"" + id + "\"&gt;" + value + "&lt;/button&gt;";
  };


  html_element["p"] = function() {
    if (typeof spec === Object) text = spec.text;
    else                        text = spec;

    return "&lt;p id=\"" + id + "\"&gt;" + text + "&lt;/p&gt;";
  };

  ...


  return html_element[type]();

}
Normally, is a good practice create sub functions instead of add all on an array.

var button = function() {

};


Always use var in front of the variables to scope to the context. (good practice).

A good choice is take advantage of the evaluation of data types on javascript, for variables.

var variable = paramValue || "defaultValue";


this evaluates paramaValue, if is true, is assigned, if not, assign "defaultValue"

Also, if is possible, considere use a template engine like:


http://handlebarsjs.com  
http://mustache.github.io


Final Code