Ad
Is This A Scope Error/leak In The JavaScript For-loop Implementation Of My Browser Or My Misunderstanding?
If I run the code below it acts as expected. (Expected being that both normal code languages AND JavaScript have "local scope" in functions) Thus the variable is not changed by the sub function.
testFunc(0);
var bFunc = function(){
for(H=1; H<5;H++){}
alert("bFunc H:"+H);
};
var testFunc = function(H){
alert("CallId 1, H: " + H);
bFunc();
alert("CallId 2, H: " + H);
};
When running the code below it fails with the variable being modified inside the sub function:
forFunc();
var cFunc = function(){
for(zzz = 0; zzz < 30; zzz++)
{}
}
var forFunc = function(){
for(zzz = 0; zzz < 5; zzz++){
alert("zzz:"+zzz);
cFunc();
}
alert("Scope leak if not 5:"+zzz);
}
Ad
Answer
In your first bit of code the H in bFunc is a global variable. The H in testFunc is not because it's an argument to the function. The zzz in your second example is always in global scope. let
const
and var
can be used to control variable scope.
var bFunc = function(){
for(H=1; H<5;H++){}
};
var testFunc = function(H){
console.log("CallId 1, window.H: " + window.H);
bFunc();
console.log("CallId 2, window.H: " + window.H);
};
testFunc(0);
var bFunc = function(){
for(let J=1; J<5;J++){}
};
var testFunc = function(J){
console.log("CallId 1, window.J: " + window.J);
bFunc();
console.log("CallId 2, window.J: " + window.J);
};
testFunc(0);
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad