0

I have two functions, let's say:

getCustomers() - get customers list getCustomerDetials() - get details of each customer

I run getCustomers() and that function runs within itself the getCustomerDetails()… Obviously, I need to list all customers and its details.

So, here goes the process.

getCustomers() loads a list of all customer ids and loops through each customer id :

for(i = 0; i < array_count; i++); 

firing the getCustomerDetails(id) on each of the customers found.

getCustomerDetails then runs its own internal loop:

for(i = 0; i < array_count; i++); 

to loop through each detail.

The problem: I had two identical for loops running both from the parent function and the function running internally.

Basically, it seems that my innter for loop "i" variable is updating the parent for loop "i" variable and it never finishes!

I changed the internal function's loop "i" variable into i2 and all was well again.

Sorry for the long explanation but i just wanted to make it clear that this is normal and expected outcome? Or there's something wrong w/ my code?

I've dealt with a few languages (I'm a seasoned PHP and AS2 programmer) and I never encountered this colision before… I'm not that good in JS though so.

1
  • Good edits @rightfold. I have, erm, asked already. Commented Apr 30, 2013 at 9:13

1 Answer 1

7

I THOUGHT variables declared inside functions stay local?

They do; the problem is that you didn't declare your variable inside the function.

Use the var keyword to declare variables:

for (var i = 0; i < array_count; i++) 

Without this keyword, you are using a global variable.


This should be covered in your JavaScript book. Which one are you using?

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

2 Comments

ahh thanks.. just wanted to confirm.. PS i dont have a JS book. just going by my current programming logic and trying to adjust/learn JS via online samples, tutorials and stuff.. got on my JS feet quickly specially since AS2, w/c i've learned via book, and been programming in for almost a decade, is very similar to JS..except for some of these quirks and stuffs such as this.. i never had this problem w/ AS2 .. and PHP for that matter. anyweh. thanks again
My question was a subtle prompt to get a book so that we don't have to repeat its contents in the form of SO answers to you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.