Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
What is missing to get correct output. I am trying to print Maximum and minimum in the array

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);
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

if you are using Javascript, then there is an alternate / easy way to find min and max of an array. Its just a one-liner

var arr = [1,4,6,3];

const min = arr.sort((a,b) => a-b)[0];
const max = arr.sort((a,b) => b-a)[0];

console.log('Original Array ==>', arr);
console.log('Min ==>', min);
console.log('Max ==>', max);

this way, you can reduce run time of your function without any for-loops and if-else loops.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!