title: How can I define a variable inside a function only the first time its called?
body: <p>I need to define a variable into a function's scope, but only the first time its called. The function will be called multiple times because it's inside a for loop, so defining a variable every time its called would make that variable unusable, since I need it to retain the value I want. I don't want to use a class, because then I would need to create a new instance of the class every time I want to use the function, and I can't use a global variable, because then multiple calls of the function would change that variable at different times and it would just make a mess. Consider this code:</p>
  
  <pre><code>for(var i = 0; i &lt; x; i++){
      myFunction(parameter1, parameter2, parameter3);
  }
  </code></pre>
  
  <p>The for loop will repeat itself x times, and the function will be called x times too. Now, consider this is the function definition:</p>
  
  <pre><code>function myFunction(parameter1, parameter2, parameter3){
      var a = 5;
      var d = 0;
  
      parameter2[d].method();
      d++;
  }
  </code></pre>
  
  <p>(This is a hypothetical situation, the unused parameters and variables should not bother you).</p>
  
  <p>Now, as you can see, I need to go through parameter2's array, but I can't do that when d is constantly being defined to 0 every time its called. I need it to be defined the first time only, and then it can be added to it. As I said, no global variables or classes, they can fix the problem but they are unpractical for my use.</p>