While I am still learning JavaScript and programming as a whole, I decided to test out some code for reversing an array using push and pop methods. Even though I am aware that I could easily utilize Array.prototype.reverse(), I wanted to have some fun experimenting.
These are the questions that came up during my experimentation:
- 1) Why do I encounter 'undefined' in the last line of code even though I returned the array?
- 2) Why does
not work and throw a 'not a function' error?ReverseStack(stack,reversed.push(stack.pop()))
- 3) Is there a way to achieve the same result without relying on a second array but only using push and pop?
const stack = [];
const reversed = [];
stack.push("a");
stack.push("b");
stack.push("c");
stack.push("d");
stack.push("e");
stack.push("f");
ReverseStack = (stack, reversed) =>{
for(let i = 0; i <= stack.length; i++) {
if (stack.length === 0){
console.log(reversed); //output [ 'f', 'e', 'd', 'c', 'b', 'a' ]
return reversed;
} else{
reversed.push(stack.pop());
ReverseStack(stack,reversed);
// This part doesn't work: it says reversed.push is not a function
// ReverseStack(stack,reversed.push(stack.pop()))
}
}
};
console.log(ReverseStack(stack, reversed)); // Outputting 'undefined' - why is that?