let array1 = [88,66,33,44,11,67,32,56];
let array2 = new Array(array1);
array1.sort();
console.log(array2);
Created an array1 with random values. Created an array2 using new keyword and initialized it with array1. Sorted array1 and printed out array2. I expected array2 to be unsorted
>Solution :
When new Array is called, a number of things can happen. See here.
- If no arguments are passed, then an empty array is created.
- If one argument is passed, and the argument is a number, a new array with a length of that number is created.
- If one argument is passed, and the argument is not a number, a new array is created, with a single value – that of the passed argument.
- If multiple arguments are passed, a new array is created, with a value for each argument.
So if you pass a single non-numeric argument, you create a new array with that one argument as a value. Passing an array as the argument results in the creation of an array which has one value, where that value is the passed array.
The value is the passed array itself, not a copy:
const array1 = [88,66,33,44,11,67,32,56];
const array2 = new Array(array1);
console.log(array2[0] === array1);
So when you sort the array (using either reference of array1 or array2[0]), because they reference the same array, you’ll see the sorted result no matter which one you examine later.
I expected array2 to be unsorted
Copy the array properly instead. Don’t use new Array.
const array2 = [...array1];