The Expressions Cheat Sheet

clamp() takes a value and makes sure it does not go beyond a certain range.

clamp(value, min, max);

Lock a point inside a rectangle

What's lovely about the clamp() function is that it also accepts arrays. This lets us clamp points in space! For example, if we wanted to make sure our layer can't leave the canvas we can apply the following expression to its Position property:

clamp(value, [0,0], [thisComp.width,thisComp.height]);

That's pretty cool! In order to describe a two-dimensional range we only need two points, the minimum and the maximum.
In this case we specify the top-left corner of the comp ([0,0]) and the bottom-right one (thisComp.width, thisComp.height).

You can modify these values to lock the Position inside any rectangular surface in and outside the view.

Clamp rotation and other one dimensional values

To clamp single-dimensional values to a range simply specify the value and the desired minimum and maximum.

clamp(value, -20, 20);