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 :
- function funA(){
- var arrA = ['a', 'b', 'c'];
- for(i=0; i<arrA.length; i++);
- //Do whatever you wish here
- return false;
- }
- function funB(arrB){
- for(i=0; i<arrB.length; i++){
- //A call to funA here that has the variable i not explicitly defined with var
- funA();
- console.log(arrB[i] + ' ' + i);
- }
- console.log('end of funB');
- }
- function execute(){
- var array = ['t', 'r', 't', 'i'];
- funB(array);
- }
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.