Redux is somehow changing my Const variables and I am flummoxed

I am running into really, really weird behavior with Redux. Basically I have a game with a static map where the player moves around on the map. The map and the player is represented by colored div’s. That’s all I’m trying to do and I was briefly able to get it working.

I create the movement by first getting the empty map (which is a hardcoded const array of arrays) and then adding the player’s (new) position at the correct coordinates. Then I render it to the view layer in React. The outputted new map with the player’s position is not named the same as the empty map.

However something very weird is happening with Redux where it is somehow changing the hardcoded const array of arrays when I render it. Putting in a ton of console.logs to see what is going on with the variables confirm that this is what is happening. Could someone please have a look at this codepen:

and teach me how to trace what on earth is going on with my mutable const?

const has a dirty little secret: It doesn’t actually make the variable immutable. What it does is disallow variable reassignment. Objects within the objects can still be mutated.

const something = { dog: "Barry" }
console.log(something.dog) // "Barry"
something.dog = "Jones"
console.log(something.dog) // "Jones"
something = "I'm a new thing!" // ERROR!

The same goes for arrays, arrays of arrays, objects of arrays, etc.

3 Likes

Didn’t know that! In retrospect, that makes sense, since objects and arrays aren’t primitive data.

Only primitive data such as String, Number, Boolean, null and undefined will give out warning if storing as const

thank you @PortableStick! resolved in the end!