Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand for if(x>y) { x=y} in javaScript

Trying to compare 2 integers' values, X and Y. If X is greater than Y, I want to cap off X at Y, like this -

if(x>y) {
    x=y;
}

Is there a shorthand way to do this (either in pure JavaScript or jQuery)? I was thinking of using a custom function, but wanted to see if something already existed.

Thanks!

like image 214
Mike Finazzo Avatar asked Jan 15 '23 05:01

Mike Finazzo


2 Answers

You can use Math.min():

x = Math.min(x, y);
like image 147
Frédéric Hamidi Avatar answered Jan 17 '23 19:01

Frédéric Hamidi


The only I can think of:

x>y && (x=y);

And fastest in Chrome 22 (thought if(...) would be faster): http://jsperf.com/if-min

like image 23
Andreas Louv Avatar answered Jan 17 '23 17:01

Andreas Louv