What's the point of lodash clamp method?

I’m doing the Codecademy lesson “Re-creating Lodash Library” and I can’t find any information on what the point is of the _.clamp method.

I read this documentation https://lodash.com/docs/4.17.15#clamp
but it did not help me at all. What does clamping a number mean? Why would I want to clamp a number?


Thank you!

seems to clamp down your number to be within the set margins, example one:

_.clamp(-10, -5, 5);
// => -5

example two:

_.clamp(10, -5, 5);
// => 5

in the first example, the number we want to clamp is -10. The minimum allowed value is -5, the max seems to be 5. So -10 gets clamped to -5

example 2 is the opposite, the number (10) is higher then the max allowed (5), so gets clamped down to 5.

Seems practical if you want to clamp down on a user input number. Lets say you run a market place website, you want to restrict the maximum price the user could set. then clamp could help. You simple restrict the max price, without having to throw an error and have the user enter another number.


Thank you for your response and the real-world example!

The practical example is just something I made up. Not sure its always desired, you might want to inform the user you are changing there input

but I couldn’t think of something better.

I have to say, I had the same question and the explanation video on YT is - well - not very helpful (to be very gentle).

That example really helps understanding why one would want to use that function. I personally would vote to find more of these real world explanations in the lessons themselves, this would make understanding much easier.

Funny story, a week or so after posting this answer, I was playing a Pokemon like game, where the health would go below zero. Nothing to annoying, but clamp would have been really useful and user friendly there.

Maybe I have been programming too long, but when I see a concept like clamp (or anything), I am instantly curious what the practical usages are.