Emmanuel Akinfulubi

JavaScriptMath

Area of a trapezoid with the shoelace formula in JavaScript

Advanced · 4 min read

A trapezoid is a four-sided shape with one pair of parallel sides, like a table seen from the side or the cross-section of a ditch. (In British English it is called a trapezium, which is why the code below uses that name.) School gives you a formula for its area. But what if you have the corner points of a field from a GPS, or the outline of a shape in a drawing app? The shoelace formula finds the area of any such polygon from its corner coordinates alone.

In this tutorial you will compute a trapezoid's area both ways and check they agree, then test the shoelace formula on a triangle, a rectangle and a pentagon. You will also see what its sign tells you, and the one kind of shape it gets wrong without warning. You need to know arrays, loops and the % operator.

The trapezoid formula

If the two parallel sides are a and b, and the distance between them is h, the area is the average of the parallel sides times the height:

Output

area = (a + b) / 2 × h

With parallel sides 8 and 5, four units apart, that is 6.5 × 4 = 26.

The shoelace formula

List the corners in order around the shape, as (x, y) pairs. For each corner and the next one, work out x1 × y2 − x2 × y1. The last corner pairs with the first. Add all those up and halve the total.

The name comes from how it looks when you write the coordinates in two columns and draw the crossing multiplications: like the laces on a shoe.

Wrapping around with %

To pair the last corner with the first, the "next" index must go back to 0. The remainder operator does that neatly:

JavaScript

const n = 4;
console.log((0 + 1) % n, (3 + 1) % n); // 1 0

For indexes 0, 1 and 2, (i + 1) % n is just i + 1. For the last index, 3, it wraps to 0.

Here is the exercise. Have a go yourself first if you like, then read on and we will build it together.

75 The shoelace formula, checked against a trapezium

hard

Find the area of a trapezium with the (a + b) / 2 * h formula, then find the same area from its four corner coordinates with the shoelace formula. Show what the sign of the unabsolute result tells you, and what the formula does with a self-crossing polygon.

Stuck? Three hints, smallest first
  1. 1. Sum x1 * y2 - x2 * y1 around the polygon, wrapping the last vertex back to the first.
  2. 2. Halve it. The sign tells you the winding direction, so take the absolute value for an area.
  3. 3. The formula assumes the edges do not cross. Nothing in it detects that they do.

Step 1: the trapezoid formula

Step 1

const trapeziumFormula = (a, b, h) => ((a + b) / 2) * h;
console.log(trapeziumFormula(8, 5, 4)); // 26

Step 2: the shoelace formula

We put the same trapezoid on a grid. The bottom side runs from (0, 0) to (8, 0), length 8. The top side runs from (1, 4) to (6, 4), length 5, four units up.

Step 2

function signedArea(points) {
  let total = 0;
  for (let i = 0; i < points.length; i++) {
    const [x1, y1] = points[i];
    const [x2, y2] = points[(i + 1) % points.length];      // wraps to the first
    total += x1 * y2 - x2 * y1;
  }
  return total / 2;
}
const trapezium = [[0, 0], [8, 0], [6, 4], [1, 4]];
console.log(signedArea(trapezium)); // 26

const [x1, y1] = points[i] unpacks a pair into two names. The result, 26, matches the trapezoid formula, from nothing but four corner points.

Step 3: what the sign means

The function is called signedArea because the answer can be negative. List the same corners the other way round:

Step 3

console.log(signedArea(trapezium.slice().reverse())); // -26

The size is the same, but the sign flips. With the y axis pointing up, as on a maths graph, positive means the corners go counterclockwise and negative means clockwise. That is a free direction test. For an area, though, you want the size only, so wrap it in Math.abs:

JavaScript

const polygonArea = (points) => Math.abs(signedArea(points));
console.log(polygonArea(trapezium.slice().reverse())); // 26

Forgetting Math.abs is the usual bug: everything works until someone lists the corners in the other order.

Step 4: check it on shapes you know

If the formula is right, it must agree with the simpler formulas:

Step 4

const triangle = [[0, 0], [4, 0], [0, 3]];
const rectangle = [[0, 0], [7.5, 0], [7.5, 4], [0, 4]];
const pentagon = [[1, 1], [4, 1], [5, 3], [3, 5], [0, 3]];
console.log(polygonArea(triangle));  // 6
console.log(polygonArea(rectangle)); // 30
console.log(polygonArea(pentagon));  // 13

The 3-4-5 triangle gives 6, as half base times height does. The 7.5 by 4 rectangle gives 30, as width times height does. The pentagon has no simple school formula, and the shoelace gives 13.

Where you start in the list doesn't matter, as long as you go around in order:

JavaScript

console.log(polygonArea([[0, 0], [1, 0], [1, 1], [0, 1]]), polygonArea([[1, 1], [0, 1], [0, 0], [1, 0]])); // 1 1

Step 5: points on a line

Step 5

console.log(polygonArea([[0, 0], [1, 1], [2, 2]])); // 0

Three points on one straight line enclose nothing, and the formula says 0.

Step 6: a shape whose edges cross

Now join four corners in an order that makes the edges cross, like a bow tie:

Step 6

const bowtie = [[0, 0], [1, 1], [1, 0], [0, 1]];
console.log(polygonArea(bowtie)); // 0

This shape is two small triangles, each with an area of 1/4, so it clearly covers something. The formula says 0. One triangle is traced counterclockwise and the other clockwise, so their signed areas cancel out.

The formula assumes the edges never cross. Nothing in it can detect that they do, so it can't warn you. If your points come from users, check the shape first.

The full solution

The answer panel has signedArea, polygonArea and trapeziumFormula, and prints the trapezoid both ways, the signed area in each direction, the triangle, rectangle and pentagon, the points on a line, and the bow tie. Press Run to see the output.

The answer

function signedArea(points) {
  let total = 0;
  for (let i = 0; i < points.length; i++) {
    const [x1, y1] = points[i];
    const [x2, y2] = points[(i + 1) % points.length];      // wraps to the first
    total += x1 * y2 - x2 * y1;
  }
  return total / 2;
}

const polygonArea = (points) => Math.abs(signedArea(points));

const trapeziumFormula = (a, b, h) => ((a + b) / 2) * h;

// Parallel sides 8 and 5, four units apart.
const trapezium = [[0, 0], [8, 0], [6, 4], [1, 4]];
const triangle = [[0, 0], [4, 0], [0, 3]];
const rectangle = [[0, 0], [7.5, 0], [7.5, 4], [0, 4]];
const pentagon = [[1, 1], [4, 1], [5, 3], [3, 5], [0, 3]];
const bowtie = [[0, 0], [1, 1], [1, 0], [0, 1]];

console.log('trapezium formula:', trapeziumFormula(8, 5, 4));
console.log('shoelace         :', polygonArea(trapezium));
console.log('signed, each way :', signedArea(trapezium), signedArea(trapezium.slice().reverse()));
console.log('triangle         :', polygonArea(triangle), 'Heron would give 6');
console.log('rectangle 7.5 x 4:', polygonArea(rectangle));
console.log('pentagon         :', polygonArea(pentagon));
console.log('collinear        :', polygonArea([[0, 0], [1, 1], [2, 2]]));
console.log('self-crossing    :', polygonArea(bowtie), '<- not a degenerate shape');

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('the trapezium formula and the shoelace formula both give 26', [trapeziumFormula(8, 5, 4), polygonArea(trapezium)], [26, 26]);
test('the signed area is positive anticlockwise and negative clockwise', [signedArea(trapezium), signedArea(trapezium.slice().reverse())], [26, -26]);
test('a 3-4-5 triangle from its corners gives 6, agreeing with Heron', polygonArea(triangle), 6);
test('the 7.5 by 4 rectangle gives 30, agreeing with width times height', polygonArea(rectangle), 30);
test('an irregular pentagon comes out at 13', polygonArea(pentagon), 13);
test('three collinear points enclose nothing', polygonArea([[0, 0], [1, 1], [2, 2]]), 0);
test('a unit square gives 1 wherever it starts in the list', [polygonArea([[0, 0], [1, 0], [1, 1], [0, 1]]), polygonArea([[1, 1], [0, 1], [0, 0], [1, 0]])], [1, 1]);
test('but a self-crossing bowtie reports 0, and it has real area', polygonArea(bowtie), 0);

The shoelace formula turns any simple polygon's vertices into its area with one pass and no trigonometry: sum the cross products of consecutive vertices and halve. It is the general case that the rectangle, triangle and trapezium formulas are special cases of, which is what the cross-checks above are for — 26 from (8 + 5) / 2 * 4 and 26 from four coordinate pairs.

Two things it will not tell you. The sign is the winding direction, positive for anticlockwise in a normal y-up coordinate system, so dropping the Math.abs gives you an orientation test for free — but forgetting it gives you a negative area when someone lists the corners the other way round, which is how the bug usually arrives. And the derivation assumes the edges do not cross: the bowtie above has two triangles of area 1/4, and their opposite windings cancel to a confident 0. Nothing in the formula detects that, so validate the polygon or accept that the answer is only meaningful for a simple one.

Common mistakes

  • Forgetting to wrap the last corner to the first. Without % points.length, the last edge is missing and the area is wrong.
  • Leaving out Math.abs. Corners listed clockwise give a negative area.
  • Listing corners out of order. The points must go around the shape. Jumping across it makes crossing edges, like the bow tie.

Try it yourself

  1. Find the area of the L-shape [[0, 0], [4, 0], [4, 1], [1, 1], [1, 3], [0, 3]]. Check it by splitting it into two rectangles.
  2. Write isClockwise(points) that uses the sign of signedArea.
  3. Move every corner of trapezium 100 units right and 50 up. Does the area change?

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.