Things to keep in mind for arrays in JS
- We know that immutability is an important factor when working in React.
- 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"
- 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"
- 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
- And from here, we go into the topic of deep copy and shallow copy.
- Reference: ES6 way to clone array