Search code examples
javascriptarrayscomputer-science

Javascript, mechanics behind pop() and push() in a array sort function


I'm working on improving my javascript skills and I want to understand the mechanics behind pop() and push(). I'm reading Marijn Haverbeke's Eloquent Javascript book and I'm working on chapter 4's Reversing Array exercise. I was able to solve the problem; however, I ran into an interesting quirk. My first code attempt was:

var arr = ['a', 'b', 'c', 'd'];

function reverseArray(array){
	var newArray = [];
	console.log(array.length);
	for(var i = 0; i <= array.length; i++){
		newArray[i] = array.pop();
	};

	return newArray;
};

reverseArray(arr);

This result was ['d', 'c', 'b'] and the the 'a' was not resolving. I don't understand why? Can someone explain?

My second code attempt was:

var arr = ['a', 'b', 'c', 'd'];

function reverseArray(array){
	var newArray = [];
	console.log(array.length);
	for(var i = array.length - 1; i >= 0; i--){
		newArray.push(array[i]);
	};

	return newArray;
};

console.log(reverseArray(arr));

This resulted in the correct reversal of the array: ['d', 'c', 'b', 'a']. Can someone explain why this worked?


Solution

  • Here lies your problem:

    for(var i = 0; i <= array.length; i++){
        newArray[i] = array.pop();
    };
    

    for each iteration:

    i = 0 array.length: 4 //d 
    i = 1 array.length: 3 //c
    i = 2 array.length: 2 //b
    i = 3 array.length: 1 //a -- wont print
    

    now your loop stops working because you told so in:-

    i <= array.length
    //3 <= 1 will return false so for loop stops
    

    Not sure if you noticed, but push() and pop() change .length property of an Array