Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Move <code>changeValue()</code> to be in the same scope as <code>i</code>:</p> <pre><code>function myFunction(){ var i; for(i=0;i&lt;3;i++){ alert(i); changeValue(); alert(i); } function changeValue() { i = 99; } } </code></pre> <p>Or, put <code>i</code> in the same scope as <code>changeValue()</code>:</p> <pre><code>var i; function changeValue() { i = 99; } function myFunction(){ // var i; // don't define i here for(i=0;i&lt;3;i++){ alert(i); changeValue(); alert(i); } } </code></pre> <p>Alternatively, you can tell <code>changeValue()</code> what the value of <code>i</code> is, then have it return the new value:</p> <pre><code>function changeValue(i) { return i + 1; } </code></pre> <p>Then:</p> <pre><code>i = changeValue(i); </code></pre> <p><strong>Edit:</strong> To illustrate scope:</p> <pre><code>var a = 0; // global scope - accessible everywhere via a // unless overridden by a locally scoped a // always accessible via window.a function doSomething () { var a = 1; // local scope - you can still access window.a var b = 2; // local scope - accessible to child scopes, but not global scope function innerFunction () { var a = 3; // you no longer have access to the parent function's a variable // you can still access window.a var c = 4; // only accessible here (since no child scopes exist) alert(window.a); // 0 alert(a); // 3 alert(b); // 2 alert(c); // 4 } innerFunction(); alert(window.a); // 0 alert(a); // 1 alert(b); // 2 alert(c); // undefined - unavailable in this scope } doSomething(); alert(window.a); // 0 alert(a); // 0 alert(b); // undefined - unavailable in this scope alert(c); // undefined - unavailable in this scope </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload