0

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;
})();
3
  • 1
    document.querySelector('.result').innerHTML =loopFunction(); Commented Jun 1, 2016 at 14:12
  • It is returned. But you are not doing anything with it: loopFunction();. eloquentjavascript.net/03_functions.html Commented Jun 1, 2016 at 14:13
  • FWIW, the IIFE is unnecessary as well as assigning to privateFunction (since the IIFE doesn't return anything). Commented Jun 1, 2016 at 14:16

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

newVar is not defined because the scope of the variable newVar is only defined in the loopFunction.

a value is in fact being returned for the loopFunction, but it is just that, a value, the variable newVar has fallen out of scope and as such is not defined in this line.

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

change this to:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.