Link to home
Start Free TrialLog in
Avatar of MJ
MJFlag for United States of America

asked on

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

ASKER CERTIFIED SOLUTION
Avatar of Tom Beck
Tom Beck
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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 ()'.
Avatar of MJ

ASKER

Tom Beck.. I do the same thing in the first example but I don't have that issue in the first example
Avatar of MJ

ASKER

I see where I redeclared at bottom. I missed that! :0)