I want to dynamically create a table from javascript and this code works fine. Is there any other method to optimize the following code?
<!DOCTYPE html>
<html>
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<head>
<title></title>
</head>
<script src="expt1.js" ></script>
<body>
<button onclick="myFunction()">Show</button>
<table id="demo"></table>
</body>
</html>
JavaScript
var myFunction = function() {
var emp = '[{ "firstName": "John", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jason" }, { "firstName": "Alice", "lastName": "Ray" }]';
var obj = JSON.parse(emp);
var table = "<tr><th>firstName</th><th>lastName</th></tr>";
for (var i = 0; i < obj.length; i++) {
table += "<tr><td>" + obj[i].firstName + "</td><td>" +
obj[i].lastName + "</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}