1

Here is my code. I am expecting "the number is 1, the number is 2..." to be out putted up to 5 but all that is outputted is the number is 0 not sure why.

<script>
var i=0;
function test(){

for(i=0;i<=5;i++){
    return "the number is" + i;
}
}
</script>
<script>
document.write(test());
</script>

2 Answers 2

5

return "the number is" + i; It (the 'point' of script execution) returns back from the function with the first loop at i = 0

Write it as http://jsfiddle.net/hNWrg/

function test(){
var out = '';
for(var i=0;i<=5;i++){
    out += "the number is" + i + "<br>";
}
return out;
}
Sign up to request clarification or add additional context in comments.

1 Comment

@AndersKitson x += 2 is the same as x = x + 2
2

your function is returning 0 the first time through the loop :-) try this:

<script>
var i=0;
function test(){

for(i=0;i<=5;i++){
    document.write("the number is" + i);
}
}
</script>
<script>
test();
</script>

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.