6 Simple JS Math Functions You Can Use Everyday.

By Kelly Milligan

Here at Thinkingbox we often need to break outside of normal browser conventions. HTML and CSS provide a great foundation, but when the goal is to create something a bit more bespoke we must turn to JavaScript.

We love these simple math functions that make things a whole lot easier; they enable us to organize complex systems into simple rules. Once you’re used to using them, you can turn to them increasingly often when solving a math or visual problem. Aces!

Sign

function sign( val ) {
return val === 0 ? 0 : val > 0 ? 1 : -1
}
// Example:
const scrollDelta = ( currentScrollY — prevScrollY )
const scrollDirection = sign( scrollDelta )

Note: There’s a native browser method for sign, however it is not supported in Internet Explorer (Edge has support though thankfully).

Clamp

function clamp( val, min, max ) {
return Math.min( Math.max( val, min ), max )
}
// Example:
const MAX_VELOCITY = 10
const clampedVelocity = clamp( velocity, -MAX_VELOCITY, MAX_VELOCITY )

Within Range

function withinRange( val, min, max ) {
return ( val >= min && val <= max )
}
// Example:
const isMouseOnLeft = withinRange(mouseX, 0, window.innerWidth / 2)

Lerp (Linear intERPolation)

function lerp( a, b, alpha ) {
return a + alpha * ( b — a )
}
// Example:
const alpha = Math.sin( performance.now() ) * 0.5 + 0.5 // cycle between 0 and 1
const positionX = lerp( 0, window.innerWidth, alpha )

Note: There are also versions of lerp that calculate 2D and 3D point interpolations, which are very useful in canvas or WebGL animation.

Degrees to Radians, Radians to Degrees

It can be much easier to reason about angles in degrees for us, so having a quick way to convert between the different angle units is helpful!

function degToRad( degrees ) {
return degrees * ( Math.PI / 180 )
}
function radToDeg( radians ) {
return radians * ( 180 / Math.PI )
}
// Example:
const progress = Math.sin( performance.now() ) * 0.5 + 0.5 // cycle between 0 and 1
const progressAroundCircle = degToRad( 360 * progress )

Note: These conversions become very useful when working with canvas or WebGL contexts, as many of their native functions for angle-based operations use radians.

Distance

function distance( x1, y1, x2, y2 ) {
const dx = x2 — x1
const dy = y2 — y1
return Math.sqrt( dx * dx + dy * dy )
}
// Example:
const proximity = distance( 0, 0, mouseX, mouseY )
if ( proximity < 200 ) console.log( ‘mouse is in upper left corner!’ );

Thinkingbox is a global creative collective shaping the future of brands through craft and curiosity.

Thinkingbox is a global creative collective shaping the future of brands through craft and curiosity.