liveBook · Manning

Remainder operation

As explained in Math for Web Design

The remainder operator is the JavaScript operator (%) that returns the remainder after division, with behavior that depends on the signs of its operands.

The remainder operator (%) returns what remains after division. It is useful for cycling through items, wrapping animation values, and keeping an index inside a fixed range—but JavaScript’s result can surprise you when the dividend is negative. section 2.5 section 2.5.1

For a five-item cycle, mathematical modulo behaves like movement around a circle:

  • 5 mod 5 = 0: completing one full cycle returns to item 0. section 2.5.1
  • 6 mod 5 = 1: moving six positions lands on item 1. section 2.5.1
  • -1 mod 5 = 4: moving backward once lands on the final item. section 2.5.1

Wrapping a carousel index safely

JavaScript gives the remainder the same sign as the dividend, so -1 % items.length is -1 rather than the final valid index. Normalize the result before indexing: function mod(dividend, divisor) { return ((dividend % divisor) + divisor) % divisor; } A back-button update can then use index = ((index - 1 + items.length) % items.length); section 2.8

How Math for Web Design covers it

How deep it goes
Explains circular modulo intuition, JavaScript’s negative-dividend behavior, and a normalization formula, then stops short of broader arithmetic internals.
Examples
Uses a five-position circle, JavaScript remainder expressions, a reusable mod function, and a carousel back-button calculation.
What it assumes
Assumes basic JavaScript expressions and division while clarifying dividend, divisor, signs, and circular movement from concrete examples.
What you can do after
Diagnose and prevent invalid cyclical indexes by normalizing JavaScript remainders before using them for navigation or animation.
How it connects
Connects the remainder operator to mathematical modulo, array indexing, carousel navigation, and animation values.

Also explained in

Compare how 3 books explain remainder operation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Math for Web Design. The section links point to the parts of the book it draws on.