+ 1

While Loop in Javascript....

function myArrayMin(arr) { var len = arr.length; var min = Infinity; while (len--) { if (arr[len] < min) { min = arr[len]; } } return min; } First explain me this code . Second tell me what does this "while(len--)" mean if it is decrement then so this condition is not going to end.

11th Apr 2020, 10:35 AM
Muhammad Awwab Khan
Muhammad Awwab Khan - avatar
1 Réponse
+ 1
The length of arr is stored in variable len. The min variable is initialised to infinity. The len-- condition will decrement the length by 1 on each run. It will run till len becomes 0. Note that while(0) is equivalent to while(false). So the loop will run till length is greater than zero. Then the code checks for the minimum element in the array. It compares each element with min, if it is less than min, min value is updated. Finally the min value is returned
11th Apr 2020, 10:59 AM
Abirame Dhevendran
Abirame Dhevendran - avatar