Adam Rajnoha Adam Rajnoha - 6 months ago 16
Javascript Question

Javascript beginner asking for code enhancement - Biggest number task

I'm learning javascript from a scratch and one online course gave me a quest to find out the biggest number from given field of numbers using javascript.

This is what I made:

function biggest(array) {
for (var i = 0; i < array.length; i++) {
if (array[i] > array[i+1]) {
if (array[i] >= array[0]) {
array[0] = array[i];
}
}
else {
if (array[i+1] >= array[0]) {
array[0] = array[i+1];
}
}
}
return array[0];
}

var array = [10,12,15,3,5,22,2];
console.log(biggest(array));


I made it on codepen here.

Could you please tell me how to make this function even better ?
I believe it's not the most efficient way, the execution context has to keep the whole array for the whole period of time, but I think that the deletion of some indexes could add on the process time.

Thanks for your suggestions.

Answer

First, make first value maximum and then check any value bigger than that, replace with the previous maximum value with the current maximum value.

like this

  var max = array[0];
  for (var i = 1; i < array.length; i++) {
    if (max < array[i])
      max = array[i];
  }
  return max;

DEMO

Comments