Search code examples
javascriptmaxlimitminimum

Is there a JS short syntax for setting maximum or minimum limit of a value


If I want to limit a value between a min and max, today I use somthing like that :

if (level > 100) level = 100;
if (level < 0) level = 0;

I'm quite sure that there should be a more elegant/fastest method to do that. If yes, what could it be ?


Solution

  • You could use this:

    var level = level > 100 ? 100 : (level < 0 ? 0 : level)
    

    It's called Conditional Statement, see this for more informations...