Wednesday, May 06, 2009

Variable Scope in JavaScript

Recently I had to add some business logic to the javascript client call back function. I had to iterate through a collection of custom business objects and update state of each of them. I made a mistake in the for loop: declared loop counter not as a local variable!
Instead of
for (var i = 0; i < myCollection.length; i++)
I had
for (i = 0; i < myCollection.length; i++)
The outcome was that I was receiving an error "__pendingCallbacks[...].async is null or not an object" every time my function was executed.


My problem was with the i variable scope. It was declared higher in the stack in the WebForm_CallbackComplete() function
for (var i = 0; i < __pendingCallbacks.length; i++)
so really I was using and updating that variable.



Weird behavior after C# where callee is not able to access its caller's local variables.

But I found my mistake pretty fast.



Hope it helps someone.
Regards,
Oleh

No comments: