Alex Alex - 6 months ago 6
HTML Question

Why can't this JS loop return a variable from inside the function

With regards to the below code, I am trying to return a variable from inside of loop. I am calling the loop from inside of a function, however when the script is run I get "Uncaught ReferenceError: newVar is not defined".

Could someone explain why the value isn't being returned?

https://jsfiddle.net/95nxwxf4/

<p class="result"></p>

var testVar = [0,1,2];

var loopFunction = function loopFunction() {

for (var j=0;j<testVar.length;j++) {
if (testVar[j]===1) {
var newVar = testVar[j];
return newVar;
}
}
return false;
};

var privateFunction = (function privateFunction() {

loopFunction();
document.querySelector('.result').innerHTML = newVar;
})();

Answer

You need to assign the value returned from loopFunction:

var privateFunction = (function privateFunction() {

  var newVar = loopFunction();
  document.querySelector('.result').innerHTML = newVar;
})();

Edit:

This is because the newVar assigned in loopFunction is scoped to that function, meaning it only exists inside that function.