2

I'm trying to write a recursive method which may take a array/value as input and then process the input.

<html>
 <body>
 <script>
 function process(array){
 if (array instanceof Array) {
 for(i=0; i < array.length; i++){
 process(array[i]);
 }
 } else {
 document.write(array + "<br />");
 }
 }
 process([3, 4, 5, [4,1], [5,1,2],[6,1]]);
 </script>
 </body>
</html>

When I try to run this program, It seems like going to an infinite loop. Why is it?

Gert Grenander
17.1k6 gold badges42 silver badges43 bronze badges
asked Aug 15, 2010 at 4:21

1 Answer 1

13

It is because of then scope of your iteration variable "i", if you declare it as a local variable the method will work fine. ex:

for(var i=0; i < array.length; i++)

If you create a variable without the "var" keyword the scope of the variable will be global(window).

In your case when the call process([4,1]) happens the value of variable i is 3, then during the call the value of the variable "i" is rested to "0" and then incremented to "1" and "2" then the processing of value [4,1] is completed and the control is given back to the caller. But since the variable "i" is of global scope the value of "i" is modified to "2" instead of "3" so this causes the main loop to process the value [4,1] again. This leads to the infinite looping.

answered Aug 15, 2010 at 4:24
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.