Home

Javascript oddity - string access as an array

Javascript oddity - accessing a string like an array

 

So I was working on a casual program for my oldest daughter the other night.   We have been sharing some bonding time over

computer game development.  She is coming up with ideas and drawing things and I have been working 

on a simple game engine for it in just Javascript and HTML.  It's a tile based 2D game and like a lot of tile based games 

it seemed like an easy idea to represent the world map with a two dimensional array of characters.  So what I first started

with was this:

 

var map = [
"000000000000000000000000000000000000000000000",
"000000000000000000000000000000000000000000000",
"000000000000000000000000000000000000000000000",
"000000000000000000000000000000000000000000000",
"000000000000000000000000000000000000000000000",
"xxxxxxxxxxxx0000000000xxx00000000xxxxxxx00000",
"xxxxxxxxxxxxxxxxx0000xxxxxxxx0000xxxxxxxxxxxx",
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ];

And everything was great.   The 0's represent blank space (sky) and the x's represent grass.

Then she wanted to be able to edit the map with the mouse, not just fiddling with characters.  I thought.. sure that's easy enough i'll

just capture the current mouse coordinates, translate to what index into the array that is and set it.

 

map[y_index][x_index] = newtile;

 

But it didn't work!!


So now i'm wondering what's going on... did mess up my indexes?  No they are correct.   Well this is easy i'll just use the old console.log()

debugger and see what's going on..

 

console.log(`newtile: ${newtile}`);
console.log(`before setting: ${map[y_index][x_index]}`);

map[y_index][x_index] = newtile;

console.log(`after setting it: ${map[y_index][x_index]}`);

What the heck! It didn't change!!

The output looks like this:

newtile: X
before setting: 0
after setting it: 0

Have I lost my mind!?

 

Well it turns out... in Javascript unbeknownst to me strings are immutable... AND even though the language will let you index into one like it's an array,

that's where things fall apart.   

 

Oddly the browser and node.js both let me carry out the above operations without any sort of error.  Even in strict mode.   This is what made this harder

to spot at first.  So while you can reference a character value with the square brackets.   You cannot change it.

 

If I had truly made a 2D array of characters this probably would not have been an issue, but I might not have learned this as soon either.