Languages
[Edit]
EN

JavaScript - keeping number variable in range

12 points
Created by:
Jun-L
533

Using JavaScript it is possible to keep variables in range in the following ways.

1. Min-Max functions example

// ONLINE-RUNNER:browser;

function keepRange(value, min, max) {
   var tmp = Math.min(value, max);
   return Math.max(tmp, min);
}


// Usage example:

//                      value  min   max
console.log( keepRange(     2,   1,  5) );  // 2
console.log( keepRange(     0,   1,  5) );  // 1
console.log( keepRange(     6,   1,  5) );  // 5
console.log( keepRange(     1,   1,  5) );  // 1
console.log( keepRange(     5,   1,  5) );  // 5
console.log( keepRange(    -2,   1,  5) );  // 1

2. Custom condition example

// ONLINE-RUNNER:browser;

function keepRange(value, min, max) {
   if (value < min) {
        return min;
   }
   if (value > max) {
        return max;
   }
   return value;
}


// Usage example:

//                      value  min   max
console.log( keepRange(     2,   1,  5) ); // 2
console.log( keepRange(     0,   1,  5) ); // 1
console.log( keepRange(     6,   1,  5) ); // 5
console.log( keepRange(     1,   1,  5) ); // 1
console.log( keepRange(     5,   1,  5) ); // 5
console.log( keepRange(    -2,   1,  5) ); // 1

Alternative titles

  1. JavaScript - how to keep number variable in range?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join