Tuesday, August 3, 2010

Javascript and Variable Scope CAPTCHAs

Today I have been doing some Javascript in order to finish some details to the Bloginto extension for Chrome, and run into a situation where two functions use a variable named i inside a for loop without explicitly defining it with the var keyword, here is an example :

  1. function funA(){
  2.             var arrA = ['a', 'b', 'c'];
  3.             for(i=0; i<arrA.length; i++);
  4.                 //Do whatever you wish here
  5.             return false;
  6. }
  7.  
  8. function funB(arrB){
  9.             for(i=0; i<arrB.length; i++){
  10.                 //A call to funA here that has the variable i not explicitly defined with var
  11.                 funA();
  12.                 console.log(arrB[i] + '  ' + i);
  13.             }
  14.             console.log('end of funB');
  15. }
  16.  
  17. function execute(){
  18.     var array = ['t', 'r', 't', 'i'];
  19.     funB(array);
  20. }

Can you tell what will be the output in the console after a call to the execute function?

My first guess was that every function has a local variable i and everything will work as it is expected, but it turns out that when not defining explicitly the variable i with the var keyword, it will be considered as a global variable, and hence funA and funB will use the same variable, hence, funB will iterate one time, incrementing i  to 1 then funA will increment it to 3, and thus, the for loop will end immediately with the output in the log screen :

i 3
end of funB

As you can see in the debugger, the variable i is defined in the same scope as funA and funB, so you have to be careful with this, because it might be the source of a lot of trouble.

javascript-debug


blog comments powered by Disqus