Could this be a variable scope problem??

Hi everyone, I can’t seem to figure out if the following problem is actually a variable scope problem or not. To undertand the problem, it’s best if you just go right ahead and take a look at the code. It’s an over simplified
version of the actual code. Pay close attention to the explanations within the code especially within the modify_b() function which is where the heart of the problem is. The problem is well described within the
explanation lines.



	$(document).ready(function() {//Check



		var a = [1,2,3,4,5];



		$("#div").click(function(){//On clicking some div, the following should happen



			var start = "yes"

			if(start != "yes"){//Alert error

				alert("error");

			}else{//Proceed


				var b = [6,7,8,9,10];



				function modify_b(){ 



					var new_b = b;//create a new array out of b array whihc we will modify below

					var c  = b.shift();//Obtain the element at begining of b array


					alert(c);//When the run_modify_b function(see below) is run, 6 is alerted, an indication that the array b is actually accessible from within this function
 
					var l = b.length; alert(l);//But when we try to obtain the length or array b, we get 0. Makes me wonder if this array is really accessible from within this function. Mind you, this same line when taken outside the fucntion, gives us the desired 5. Same thing happes with new_b

					for(var i=0;i<b.length;i++){alert(b[i]);}//Obviously, this line (which is what I originally wanted to to do with my function), does nothing as b.length is 0. Again, when taken outside the function, this line alerts the desired 6,7,8,9,10

					if($.isArray(b)){alert("aye!");}else{alert("nay!");}//Alerts aye!, an indication that b (also new_b) is actually recognized as an array within this function. So why in the world can't normal array methods be performed on this array?? Beats me.

					//Now I tested all the above functions on array a and got the desired results as follows

					var l = a.length; alert(l);//alerts 5

					for(var i=0;i<a.length;i++){alert(a[i]);}// alerts 1,2,3,4,5



				}//End of modify b function



				
				function run_modify_b(){

					modify_b();

				}//End of run modify b function


				//Run the run modify b function. This may appear redundant but in the original code, there is much more than just this one line 

				run_modify_b();	

										

			}//End of else  proceed.




		});//End of div click function



	});//End document ready method	



So, Im really confused. Is this a variable scope problem where the modify_b() function cant access the b variable (i really don’t see any reason why), in which case, why would it even be modifiable within that function or why would it be recognized as an array? please help.

Sponsor our Newsletter | Privacy Policy | Terms of Service