Things to keep in mind for arrays in JS

  1. We know that immutability is an important factor when working in React.
  2. The thing with arrays in JS is that, they are reference values.

CODE:

const arr = [20, 1, 2, 100];
const getSortedArray = (array) => array.sort((a, b) => a - b);
console.log("arr: " + arr);
console.log("array: " + getSortedArray(arr));
console.log("arr: " + arr);

OUTPUT:

"arr: 20,1,2,100"
"array: 1,2,20,100"
"arr: 1,2,20,100"
  1. Thus, using = operator for copying array won't work. For this, we can use the spread operator.

CODE:

console.log("array: " + getSortedArray([...arr]));

OUTPUT

"arr: 20,1,2,100"
"array: 1,2,20,100"
"arr: 20,1,2,100"
  1. Using the spread operator will only take you so far though. Because, it only takes us one level deep. So, it is good for 1 dimensional arrays. Otherwise not
  2. And from here, we go into the topic of deep copy and shallow copy.
  3. Reference: ES6 way to clone array