cleaning up and increasing performance of js code I would like to increase my performance of js code write a clean code... can you tell me how to do it... providing my fiddle below with js code...

http://jsfiddle.net/YYg8U/

var myNumbersToSort = [-1, 2, -3, 4, 0.3, -0.001];

function getClosestToZero(numberSet) {
    var i = 0, positiveSet = [], positiveClosest = 0;
    for (i = 0; i &lt; numberSet.length; i += 1) {
        positiveSet.push(numberSet[i] &gt;= 0 ? numberSet[i] : numberSet[i] * -1);
    }
    positiveClosest = Math.min.apply(Math, positiveSet);
    return numberSet[positiveSet.indexOf(positiveClosest)];
}

alert(getClosestToZero(myNumbersToSort));
In code you posted, you pass through array three times instead of one:


1st pass when pushing absolute values to auxillary array
2nd pass when searching for minimum value (in Math.min)
3rd pass when you get the index of minimum value (in indexOf)


It is more efficiently to do it in just one pass:

function getClosestToZero(set) {
  if(0 === set.length) return null;
  var closest = Math.abs(set[0]), result = 0;
  for(var i in set) {
     var next = Math.abs(set[i]);
     if(closest &gt; next) {
       result = i;
       closest = next;
     }
  }
  return result;  
}


Also for the purpose of readability I will recommend you to use Math.abs library function instead of implementing it by yourself.

Note: The small theoretical disatavantage of my code consists in that it compares first element with itself. You can rewrite for loop to avoid it or ignore it because its impact is insigninficant.