Why do I get an infinite loop when I don't define parameters?

I would like to know why I get an infinite loop here. I just do not want to pass these initial values, so if they are undefined , they are automatically calculated. Its easy to clear my function call to use only one parameter. If I pass them, everything will work fine and the process will end. Can anyone help? Thanks

 function merge(array, lower, half, upper){ //Suppressed for the sake of brevity } function mergeSort(array, lower, upper){ if(!lower && !upper){ //take a look here lower = 0; upper = array.length - 1; } if(lower < upper){ var half = Math.floor((lower + upper)/2); mergeSort(array, lower, half); mergeSort(array, half + 1, upper); merge(array, lower, half, upper); } } var array = [8, 3, 6, 4, 1, 0, 23, 12, 15, 63]; mergeSort(array); //infinite loop here console.log(array); 
+6
source share
1 answer

Your very first recursive call to mergeSort passed it 0 as the first argument, because you set it like this.

since !0 also evaluates to false , here you go.

Better check undefined with typeof operator

 if(typeof lower === 'undefined' && typeof upper === 'undefined'){ //take a look here lower = 0; upper = array.length - 1; } 

or better yet check arguments.length for example

 if( arguments.length === 1 ) { var lower = 0, upper = array.length -1 ; } 
+7
source

Source: https://habr.com/ru/post/921223/


All Articles