Alex Alex - 1 year ago 64
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?

<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() {

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

Answer Source

You need to assign the value returned from loopFunction:

var privateFunction = (function privateFunction() {

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


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download