Concatenating strings with `if` statements in JavaScript

data = "<html>\n<head>\n" 
    + (
        typeof metadata_title !== "undefined" ?
        "<title>" + metadata_title + "</title>\n" :
        ""
    )
    + (
        typeof metadata_author !== "undefined" ?
        "<meta name=\"author\" content=\"" + metadata_author + "\"></meta>\n" :
        ""
    )
    + (
        typeof metadata_date !== "undefined" ?
         "<meta name=\"date\" content=\"" + metadata_date + "\"></meta>\n" :
        ""
    )
    + "</head>\n<body>\n\n" 
    + paras.join("\n\n") 
    + "\n\n</body>\n</html>";

I might do something a little different (a little more akin to templating), mainly because I hate concatenated HTML done with Javascript:

var metadata_title = "Hello";
var metadata_author = "Me";
var metadata_date = "2011-09-07";

var template = "<html>\
            <head>\
                <title>#title#</title>\
                <meta name=\"author\" content=\"#author#\"></meta>\
                <meta name=\"date\" content=\"#date#\"></meta>\
            </head>\
            <body>\
            </body>\
            </html>";

var data = template.replace("#title#", metadata_title != undefined ? metadata_title : "")
                   .replace("#author#", metadata_author != undefined ? metadata_author : "")
                   .replace("#date#", metadata_date != undefined ? metadata_date : "");

Sure, there's a very small amount of additional overhead, but to me, it's way more readable.


I'd use a ternary operator:

data = "<html>\n"
     + "<head>\n" 
     + ( typeof metadata_title  !== "undefined" ?  "<title>" + metadata_title + "</title>\n"                             : "" )
     + ( typeof metadata_author !== "undefined" ?  "<meta name=\"author\" content=\"" + metadata_author + "\"></meta>\n" : "" )
     + ( typeof metadata_date   !== "undefined" ?  "<meta name=\"date\" content=\"" + metadata_date + "\"></meta>\n"     : "" )
     + "</head>\n"
     + "<body>\n"
     + "\n"
     + paras.join("\n\n")
     + "\n"
     + "\n"
     + "</body>\n"
     + "</html>"
;