Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use javascript to get the highest value of two variables

Tags:

javascript

I have two variables name var h1 and var h2 each holds some numbers. i want to get highest value to another variable

like image 371
Hareesh Avatar asked Oct 23 '25 01:10

Hareesh


2 Answers

Try this to get the maximum:

var result = Math.max(h1,h2)
like image 116
davids Avatar answered Oct 24 '25 16:10

davids


var highestNum = h1 > h2 ? h1: h2;

or if you dislike tertiary statements:

var highestNum;
if (h1 > h2) { 
    highestNum = h1;
} else {
    highestNum = h2;
}

Edit: Interestingly enough, it appears the if-else statement runs much faster than Math.max (on Chrome 21)

http://jsperf.com/jbabey-math-max

like image 33
jbabey Avatar answered Oct 24 '25 16:10

jbabey