Home > OS >  What is missing to get correct output. I am trying to print Maximum and minimum in the array
What is missing to get correct output. I am trying to print Maximum and minimum in the array

Time:12-04

When I run this code in browser console or any JavaScript environment, I get max and min as 1,1. Could someone help me to find the error.

var arr = [1,4,6,3];
function maxAndMin(arr) {
var max = arr[0];
var min = arr[0];
for(var i=0; i < arr.lenght; i  ) {
  if(arr[i] > max) {
  max = arr[i];
}
  if(arr[i] < min) {
  min = arr[i];
}}
console.log("Max:",max,"Min:",min);
}  

 maxAndMin(arr);

CodePudding user response:

arr.lenght has a typo, and is returning an undefined back. So you never iterate the for loop.

CodePudding user response:

You had a typo with lenhgt. Also, I recommend starting your loop from 1, since the 0'th element is already processed at initialization time.

    var arr = [1,4,6,3];
    function maxAndMin(arr) {
    var max = arr[0];
    var min = arr[0];
    for(var i=1; i < arr.length; i  ) {
      if(arr[i] > max) {
      max = arr[i];
    }
      if(arr[i] < min) {
      min = arr[i];
    }}
    console.log("Max:",max,"Min:",min);
    }  

     maxAndMin(arr);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related