1

I am having trouble printing a simple array list in javascript. undefined is being printed before only two array items. please consider the code below;

function buildList(){
    var box = document.getElementById("box");
	var startList  = "<ol>";
	var endList = "</ol>";
	var listItems;
      
        var arry = ["Go to shopping", "Go to Mall"];
  	for(var i = 0; i < arry.length; i++){
            listItems += "<li>" + arry[i] + "</li>";
	}

	box.innerHTML = startList + listItems + endList;
}
document.onLoad(buildList());``
          
<div id="box">
  
</div>

output of this is

undefined 1) Go to shopping 2) Go to Mall

Please help.

2
  • You forgot to initialize listItems Commented Aug 14, 2015 at 20:29
  • Hi @knight, if any answer has solved your question please consider accepting it by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. Commented May 6, 2016 at 11:32

4 Answers 4

6

Your listItem variable is undefined because it is not initialized.

var listItems = "" ; (at line 5) should solve your problem.

Sign up to request clarification or add additional context in comments.

Comments

3

You are declaring var listItems; => undefined, you should do as follows: var listItems = ""; => declared and initialized as an empty string.

Comments

2

You have to initialize listItems.

var listItems = "";

What you are doing right now is adding a string to listItems, but you did not define listItems. It does not know what is listItem

Comments

0

Try this. In your code you missing var listItems="";

Here is full code

function buildList()
       {
	   var box = document.getElementById("box");
	   var startList  = "<ol>";
	   var endList = "</ol>";
	   var listItems="";

	   var arry = ["Go to shopping", "Go to Mall"];

	    for(var i = 0; i < arry.length; i++)
	    {
		listItems += "<li>" + arry[i] + "</li>";
	   }

	  box.innerHTML = startList + listItems + endList;
      }

       document.onLoad(buildList());``
          
<div id="box">
  
  </div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.