JQuery for loop & array - Why is this variable undefined?
<p>I'm following a snake game tutorial. I put 'snake_array.pop()' inside the 'paint()' function for-loop to see what would happen, and I'm trying to understand why I'm getting the following error:</p>

<p>"Uncaught TypeError: Cannot read property 'x' of undefined"</p>

<p>I don't see why 'x' is undefined. The last iteration of the paint() for-loop makes c = snake_array[2], and snake_array[2] is {x:2, y:2}. So why does it state that x is undefined?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function(){
  
var canvas = $("#canvas")[0];
var ctx = canvas.getContext("2d");
var w = $("#canvas").width();
var h = $("#canvas").height();

ctx.fillStyle = "white";
ctx.fillRect(0, 0, w, h);
ctx.strokStyle = "black";

var snake_array;

create_snake();
function create_snake()
{
  var length = 5;
  snake_array = [];
  for(var i = length - 1;i&gt;=0;i--)
    {
      snake_array.push({x:i,y:2});
    }
}
  
function paint()
{
  
  for(var i=0; i &lt; snake_array.length; i++)
    {
      var tail = snake_array.pop();
 
   var c = snake_array[i];
   ctx.fillStyle = "blue";
   ctx.fillRect(c.x*10, c.y*10, 10, 10);
   ctx.strokeStyle = "white";
   ctx.strokeRect(c.x*10, c.y*10, 10, 10);
      
    }
}
paint();
  
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;
&lt;canvas id="canvas" width="450" height="450"&gt;&lt;/canvas&gt;</code></pre>
</div>
</div>
</p>