Increment the neighbors of a cell in a matrix
Like Simon I would store the directions into a data structure, though I would probably hard code it

//Array Index Constants
var X = 0 , Y = 1; 
//All 8 neighbours ( vectors )
var vectors = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]];


The fun thing about JavaScript is that there is no ArrayIndexOutOfBoundsException in JavaScript, requesting a value out of bounds returns undefined.

So, now, you can go for 

for( int i = 0 ; i &lt; vectors.length ; i++ ){
  var vector = vectors[i];
  if( m[x+vector[X]] &amp;&amp; m[x+vector[X]][y+vector[Y]] !== undefined )
    m[x+vector[X]][y+vector[Y]]++;  
}


I did use for m[x+vector[X]] a falsey comparison, if the row X was defined it would pass the falsey evaluation ( it would be an Array ). For m[x+vector[X]][y+vector[Y]] I compared to undefined, since 0 is a realistic, acceptable value which would evaluate as false.

If I had to do a lot of matrix magic, then I would have a dedicated function to check whether a point is part of the matrix. And a dedicated function to add a vector to a point.