In an attempt to prepend an element to a new array and return the modified array, I wrote the following code. Although it works, returning the original 'arr' instead of the modified 'newArr' results in changes to the 'arr'.
function addToFrontOfNew(arr, element) {
newArr = arr;
newArr.unshift(element);
return newArr;
}
If I were to modify the code as shown below:
function addToFrontOfNew(arr, element) {
newArr = arr;
newArr.unshift(element);
return arr;
}
And then test the function with addToFrontOfNew([1,2], 3), the output would be [3, 1, 2].
I'm seeking guidance on how to restructure the function so that only the 'newArr' is modified without affecting the original 'arr'.