My recent assignment involves exploring scope and mutability concepts in JavaScript:
The task at hand is to create two functions, reverseArray and reverseArrayInPlace. The first function, reverseArray, takes an array as input and returns a new array with elements in reverse order. The second function, reverseArrayInPlace, should modify the original array to reverse its elements without using the built-in reverse method.
I successfully implemented the reverseArray function but encountered difficulties while working on the reverseArrayInPlace function. I tried multiple approaches, some of which failed, and now I'm looking for insights into why certain methods are unsuccessful. Although there are alternative ways to achieve the desired outcome, I am keen on understanding the behavior of my existing code.
// Function that reverses input array and outputs a NEW reversed array.
function reverseArray(myArray){
var reversedArray = [];
for(var i=0; i<myArray.length; i++){
reversedArray.unshift(myArray[i]);
}
return reversedArray;
}
/*
Reverse the original array in place
*/
// Approach 1: UNSUCCESSFUL
function reverseArrayInPlace1(myArray){
myArray = reverseArray(myArray);
}
// Approach 2: UNSUCCESSFUL
function reverseArrayInPlace2(myArray){
var original = [];
for (var i=0; i<myArray.length; i++) {
original[i]=myArray[i];
}
myArray = reverseArray(original);
}
// Approach 3: SUCCESSFUL
function reverseArrayInPlace3(myArray){
var original = [];
for (var i=0; i<myArray.length; i++) {
original[i]=myArray[i];
}
var newArray = reverseArray(original);
for (var i=0; i<myArray.length; i++) {
myArray[i]=newArray[i];
}
}
miArreglo = ["a", "b", "c", "d" ];
console.log("Original Array: ", miArreglo);
reversedArray=reverseArray(miArreglo);
console.log("Reversed using reverseArray function: ", reversedArray);
reverseArrayInPlace1(miArreglo);
console.log("Reversed using reverseArrayInPlace1 function: ", miArreglo);
reverseArrayInPlace2(miArreglo);
console.log("Reversed using reverseArrayInPlace2 function: ", miArreglo);
reverseArrayInPlace3(miArreglo);
console.log("Reversed using reverseArrayInPlace3 function: ", miArreglo);