Random commas appear in array ReactJS

Keywords´╝Ü javascript arrays reactjs random comma


I am trying to create this memory game in ReactJS and I have made an array in which I add 4 random numbers. Now everytime I press play game I need to fill the array with 4 random numbers 0 to 3 but I keep getting random commas that come out of nowhere in the array. I am quite new to React so any help is appreciated.

I have tried different methods of filling up the array but the commas still appear. Ps. keepArray was initialized just before the for loop.

for (let i = 0; i < 4; i++) {
      let rand = Math.floor(Math.random() * 4)
      keepArray = [...keepArray + rand]

Screenshot of run: http://prntscr.com/nx9sqg




keepArray = [...keepArray + rand]


keepArray = [...keepArray, rand]


The spread operator (...) is literally "spreading" your array, that's why you need commas. The example bellow may help to visualize it:

// Let's start with a simple array:
var myArray = [1, 2, 3];

// Now, we add another element to it using spread:
var updatedArray = [...myArray, 4];

// Here, ...myArray is translated to [1, 2, 3]
// That means that the above could be read as:
var updatedArray = [1, 2, 3, 4];

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

The above answer does fix the problem, but the real reason for the behaviour is as follows.

The + operator is overloaded to serve the purposes of both number addition and string concatenation. When + receives an object (including array in your case) for either operand, it first calls the ToPrimitive abstract operation on the value, which then calls the [[DefaultValue]] algorithm with a context hint of number. Which intern calls toString method on the array.

var val = [1,2,3] + 1;
console.log(val); // "1,2,31"

And then you are trying to spread that string in an array like so,

var arr = [...val];
console.log(arr); // ["1", ",", "2", ",", "3", "1"]

this is the actual reason why you are seeing those commas.