Search code examples
javascriptalgorithmsortingmergemergesort

javascript merge/sort fatal error


I was writing the merge sort algorithm, and in the merge helper function, I had the following comparison statement:

    function merge(a,b){
        var result = [];
            while(a.length && b.length){
                    result.push(a[0] < b[0] ? a.shift() : b.shift()); // you can't just grab a[0] or b[0] 
        //as it results in a fatal error.
                }
return, etc.
}

Why is it that when instead of 'a.shift()', I typed a[0], it resulted in a fatal error? Is it because you are doing something with something that's also in a conditional clause?


Solution

  • Checkout the documentation for shift. It removes the first element. So if you only access a[0] and don't remove it then the while loop never exits.