Two-dimensional Arrays Javascript giving indefinite before printing other arrays

advertisements

Why I am getting undefined printed before list items. Don't where I am making mistake. Please help me out. Please consider the code snippet below

var playList = [
      ["Wild Ones", "Flo Rida"],
      ["Wings", "Birdi"],
      ["Pure Love", "White Lion"],
      ["Hold my hands", "Jess Glynn"]
    ];

var listSongs = "</ol>";
 function print(msg)
{
  document.write("<p>" + msg + "</p>");
}

function printSongs( songs )
{
  for(var i = 0; i < songs.length; i++)
    {
      listSongs += "<li>" + songs[i][0] + " " + ", by " + songs[i][1] + "</li>";
    }

  listSongs += "</ol>";
  print(listSongs);
}

var box = document.getElementById("container");

document.onLoad(box.innerHTML = printSongs(playList));
<div id="container">

  </div>

Why before songs list undefined is being printed. Please help


That's because the printSongs function doesn't return any specific value. If you don't specify a return value, the function will return the value undefined.

As you are running the code from the load event (or at least try to), you shouldn't use document.write. Once the page is loaded, using document.write will implicitly call window.open so that a new page is created which will replace the current page.

Return the HTML code from the function instead of writing it out:

var playList = [
  ["Wild Ones", "Flo Rida"],
  ["Wings", "Birdi"],
  ["Pure Love", "White Lion"],
  ["Hold my hands", "Jess Glynn"]
];

function print(msg) {
  return "<p>" + msg + "</p>";
}

function printSongs(songs) {
  var listSongs = "<ol>"; // should be starting tag, not an ending tag
  for(var i = 0; i < songs.length; i++) {
    listSongs += "<li>" + songs[i][0] + " " + ", by " + songs[i][1] + "</li>";
  }
  listSongs += "</ol>";
  return print(listSongs);
}

// The property is named onload, not onLoad, and it's in the window object
// It's not a function, you assign a function to it
window.onload = function() {
  // get the element inside the load event handler
  var box = document.getElementById("container");
  box.innerHTML = printSongs(playList);
};
<div id="container"></div>