0
<head>
<script>
function whammo()
{
    var i = 1;
    while(i<=5)
    {
        document.write("<h6>Test</h6>");
        i=i+1;
    }
}
</script>
</head>
<body>

<div id='page'></div>
<script>
document.getElementById('page').innerHTML = whammo();
</script>

</body>

The whammo function is to return 5 h6 Tests to be displayed, but it returns the following: undefined Test Test Test Test Test

I did my testing here: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_elmnt_innerhtml

Why is undefined being returned?

2 Answers 2

3

You need to create a string, and return the value from whammo

function whammo()
{
    var i = 1, html = '';
    while(i<=5)
    {
        html  += "<h6>Test</h6>";
        i=i+1;
    }
    return html
}

Demo: Fiddle

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

1 Comment

You're right, I suppose it tried to print the function return. So obvious now. Thank you for your help. I wish I had more rep so I could upvote you.
1

this one is shorter (and Arun P Johny forgot semicolon in the end)

function whammo() {
    for (var i=0, html=''; i<=5; i++) {
        html += '<h6>Test</h6>';
    }
    return html;
}

also, a piece of advise, use jsfiddle to show your own examples: http://jsfiddle.net/vladkras/y2vbk/ instead of w3school

3 Comments

ArunPJohny was using the OP's code as much as possible in order to highlight the actual change they were making. Refactoring the entire function obscures what was fixed. The semicolon is recommended, but not strictly required.
You also ended up with an extra pass through the loop.
1. you are right, I saw extra loop comparing my and ArunPJohny's fiddles but decided to leave as is, because the topicstarter tries to insert "test" multiple times, not exactly 5 times (also I'm a lil bit lazy, sorry), so I didn't think it's really important 2. I always try to follow recommendations, i think it's a good practice

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.