Instead of using the pop method, you can achieve the same result by iterating through the existing array in reverse order to create a new one.
function reverseArray(array){
var output = [];
for (var i = array.length - 1; i>= 0; i--){
output.push(array[i]);
}
return output;
}
console.log(reverseArray([1,2,3,4,5,6,7]));
Edit after answer was accepted:
A comment with a link on your original post motivated me to compare my approach against the accepted answer. Surprisingly, my method consistently proved to be faster in my tests. Although the difference was minimal, my way outpaced the other every time.
Below is the code snippet I used to conduct the comparison (tested in Firefox developer scratch pad):
function reverseMyMethod(array){
var output = [];
for (var i = array.length - 1; i>= 0; i--){
output.push(array[i]);
}
return output;
}
function reverseTheirMethod(array) {
var output = [];
while (array.length) {
output.push(array.pop());
}
return output;
}
function RunningSpeedTest(){
console.log("Testing their method")
var start = new Date().getTime();
for(var p = 0; p < 10000; p++)
{
console.log(reverseTheirMethod([7,6,5,4,3,2,1]))
}
var end = new Date().getTime();
console.log("Total runtime: " + (end - start) + " ms");
console.log("Finished testing their method")
}
function RunningSpeedTestMyWay(){
console.log("Testing my method")
var startingTime = new Date().getTime();
for(var p = 0; p < 10000; p++)
{
console.log(reverseMyMethod([7,6,5,4,3,2,1]))
}
var endingTime = new Date().getTime();
console.log("Total runtime: " + (endingTime - startingTime) + " ms");
console.log("Finished testing my method")
}
RunningSpeedTest();
RunningSpeedTestMyWay();