Anonymous Function Variable Scope Issue

I'm confused by this?!?!? IF I run the following test code, the variable "loadCode" gets changed to "true" by the setTesting function
(function () { 
     var loadCode = false;
	 
	setTesting = function (){
	    loadCode = true;
		return true;
	};
	
	if (!setTesting()){
       console.log("not in test mode");
	}
	
	if(loadCode){ 
		console.log("in TEST Code");
     }
})();

Open in new window

Now if I run this code below, the variable "loadCode" switches back to false after leaving the setTesting function and I don't understand why? What am I missing?
(function () { 

    var loadDTM = false;
    var testDTM = false;
		
	setTesting = function (){
	    if (localStorage.getItem("testdtm") || -1 !== location.href.indexOf("#testdtm")){
	        localStorage.setItem("testdtm", !0);
		    testDTM = true;
		    loadDTM = true;
			return true;
	    }
		
		if (localStorage.getItem("testsample") || -1 !== location.href.indexOf("#testsample")){
	        localStorage.setItem("testsample", !0);
		    testDTM = false;
		    loadDTM = true;
			return true;
	    }
		
		var loadDTM = false;
	    var testDTM = false;
		return false;
	};
	
	if (!setTesting()){
     console.log("Not in testing");
	}
	
	if(loadDTM){ 
	    console.log("in DTM load");
 	}
})();

Open in new window

894359Asked:
Who is Participating?
 
Tom BeckCommented:
In the second example you are changing the global scope of the original loadDTM and testDTM by re-declaring them inside the function and setting them to false. Inside the function, they are now local and separate variables from the global versions. The global then remains false when testing loadDTM for true in the conditional at the end.
0
 
Dave BaldwinFixer of ProblemsCommented:
That's weird.  And there is no 'setTesting()' function in your code (referenced on line 26 above).  There is only a 'setTesting' variable.  'setTesting' function would be " function setTesting ()", not 'setTesting = function ()'.
0
 
894359Author Commented:
Tom Beck.. I do the same thing in the first example but I don't have that issue in the first example
0
 
894359Author Commented:
I see where I redeclared at bottom. I missed that! :0)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.