JavaScript: Limit a value inside a certain range
JavaScript Math: Exercise-37 with Solution
Write a JavaScript function to limit a value inside a certain range.
Note : If the value is higher than max it will return max. and if the value is smaller than min it will return the min.
Test Data :
console.log(value_limit(7, 1, 12));
7
console.log(value_limit(-7, 0, 12));
0
console.log(value_limit(15, 0, 12));
12
Sample Solution:
JavaScript Code:
// Define a function named value_limit that restricts a value within a specified range.
function value_limit(val, min, max) {
// If val is less than min, return min; otherwise, if val is greater than max, return max; otherwise, return val.
return val < min ? min : (val > max ? max : val);
}
// Output the result of restricting the value 7 within the range [1, 12] to the console.
console.log(value_limit(7, 1, 12));
// Output the result of restricting the value -7 within the range [0, 12] to the console.
console.log(value_limit(-7, 0, 12));
// Output the result of restricting the value 15 within the range [0, 12] to the console.
console.log(value_limit(15, 0, 12));
Output:
7 0 12
Visual Presentation:
Flowchart:
Live Demo:
See the Pen javascript-math-exercise-37 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript function which will return values that are powers of two.
Next: Write a JavaScript function to check if a number is a whole number or has a decimal place.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/javascript-exercises/javascript-math-exercise-37.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics