How to push new elements in an array as they increase in number?

I have a gird with a few nodes. As I move my mouse on the gird, the values of row and col change.

For example:

  const handleMouseEnter = (row, col) => {
    console.log(row, col);
  };

this code returns this on the console:

enter image description here

These are the coordinates.


The question is: How do I store these values in an array as they grow? I tried to do it with the push function like this:

  const handleMouseEnter = (row, col) => {
    const coordinatesVisited = [];
    coordinatesVisited.push(row, col);

    console.log(coordinatesVisited);
  };

but it just returns me this:

enter image description here

I want all these arrays in one single array at the end. The grid is small so performance issues won’t be any problem. The array can be overwritten again and again.

EDIT: With this code, 1-2 values are logged only while the log statement is inside the function but nothing stays.

  const coordinatesVisited = [];
  const handleMouseEnter = (row, col) => {

    coordinatesVisited.push([row, col]);

  };
  console.log(coordinatesVisited);

Outside of the function, it is still an empty array.

This is probably a very simple question but right now I can’t think of the solution.

Answer

Because each time const declare new array variable. So you need to declare array on before function call like global variable

 const coordinatesVisited = []; // declare as global
 const handleMouseEnter = (row, col) => {
    coordinatesVisited.push(row, col);
    console.log(coordinatesVisited);
  };