title: How to loop through all neighbors of a cell in a board represented by 2-dimensional array?
body: <p>Building Game of Life here and working on a function to loop through all the neighbors of a cell and sum up the scores (each cell is 0 or 1). Board is represented by a 2-dimensional array. Normally a cell has 8 neighbours. The problem is that cells in the corner of the board have only 3 neighbors and cells on the side have 5. If I loop through the array using the code below, some neighbors return undefined in the array. I want to convert undefined to 0 and use that to sum up the scores, but i get the error:</p>
  
  <p><em>Uncaught TypeError: Cannot read property '-1' of undefined</em></p>
  
  <p>Thanks for your help!</p>
  
  <pre><code>var array = [
      [0,0,1,0,1,0,1,0,1,1],
      [0,0,1,0,1,0,1,0,1,1],
      [0,0,1,0,1,0,1,0,1,1],
      [0,0,1,0,1,0,1,0,1,1],
      [0,0,1,0,1,0,1,0,1,1],
      [0,0,1,0,1,0,1,0,1,1],
      [0,0,1,0,1,0,1,0,1,1],
      [0,0,1,0,1,0,1,0,1,1],
      [0,0,1,0,1,0,1,0,1,1],
      [0,0,1,0,1,0,1,0,1,1]
  ]
  
  for(var i=0; i &lt; array.length; i++){
      for(var j=0; j &lt; array[i].length; j++){
  
      var totalScore = 0;        
      var scores = [
          //i = row in loop
          //j = column nested loop  
          array[i-1][j-1],
          //upper left corner
          array[i-1][j],
          //top side
          array[i-1][j+1],
          //upper right corner
          array[i][j-1],
          //left side
          array[i][j+1],
          //right side
          array[i+1][j-1],
          //bottom left corner
          array[i+1][j],
          //bottom side
          array[i+1][j+1]
          //bottom right corner
          ];
  
          scores.forEach(function(item){
  
                var score = item;
                if(score === "undefined"){
  
                  score = 0;
  
                }
  
                totalScore += score;
  
              })
  
              console.log(totalScore);    
  
      }
  
  }
  </code></pre>