I am working on a game with a number of different grid components. Each grid would be about 15 squares wide by 15 squares tall. Each of the squares may either contain an item or not.

Is there any way to create this array and only include the components that have a value. Example (for a 5x5 array):

   [5,3, , ,3],
   [ ,1,0,2,2],
   [ , , , , ],
   [5, , ,2, ],
   [ , , , ,1]

Is there any way to do this in JavaScript or should I just add a bunch of NULL values to the array?

A simplified version of this, might be an Xs and Os game. Before the game starts all squares are empty. Over time, some of the grid may have either Xs or Os in specific squares.

  • 1
    \$\begingroup\$ adding the null values sounds perfect. I was thinking in your X and O's example you could just have 0 = empty; 1= X, 2 = o or whatever feels right to you \$\endgroup\$ Jul 1, 2019 at 8:58
  • \$\begingroup\$ Did you try using null values? If it worked, post it as an answer. If you're worried that's the "wrong" way to do it, ask yourself, what do you expect the array to return if you try to read one of those blank entries? \$\endgroup\$
    – DMGregory
    Jul 1, 2019 at 14:47
  • \$\begingroup\$ @DMGregory I guess the issue was that I was wanting to look at the array and see it the same way I would see it on the screen so that I could easily see at a glance which areas of the array had something in them or not. I guess it's not a big deal though and I will just use null values. It would have just helped me to visualize things better. \$\endgroup\$
    – kojow7
    Jul 1, 2019 at 17:36

1 Answer 1


If you want the map to appear as close as possible to what you've written above, without a lot of nulls to type out and clutter reading, you could define a helper variable first:

var _ = null;

var tileMap = [
  • \$\begingroup\$ Thank you, I didn't realize that a single underscore could be used as a variable name. \$\endgroup\$
    – kojow7
    Jul 1, 2019 at 19:03
  • 1
    \$\begingroup\$ I don't recommend it as a general practice, but for a special case like this, if it helps you read and edit your code to get the behaviour you want, it could be worthwhile. :) \$\endgroup\$
    – DMGregory
    Jul 1, 2019 at 19:07
  • \$\begingroup\$ huh that's interesting \$\endgroup\$
    – Ocelot
    Jul 3, 2019 at 6:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .