Finding the length of the diagonal of a cuboid using JavaScript

We need to write a JavaScript function that calculates the diagonal length of a cuboid (rectangular box) given its length, width, and height dimensions.

Problem

We are required to write a JavaScript function that takes in the length, width and height of a cuboid and return the length of its diagonal.

Formula

The space diagonal of a cuboid is calculated using the 3D Pythagorean theorem:

diagonal = ?(length² + width² + height²)

Example

Following is the code:

const height = 10;
const width = 12;
const length = 15;

const findDiagonal = (l, w, h) => {
    const ll = l * l;  // length squared
    const ww = w * w;  // width squared  
    const hh = h * h;  // height squared
    const sum = ll + ww + hh;
    const diagonal = Math.sqrt(sum);
    return diagonal;
};

console.log(findDiagonal(length, width, height));

Output

22.671568097509267

Simplified Version

We can make the function more concise:

const findDiagonal = (l, w, h) => {
    return Math.sqrt(l*l + w*w + h*h);
};

// Test with different dimensions
console.log(findDiagonal(3, 4, 5));   // Simple case
console.log(findDiagonal(15, 12, 10)); // Our example
console.log(findDiagonal(1, 1, 1));    // Unit cube
7.0710678118654755
22.671568097509267
1.7320508075688772

Visual Representation

Length Height Width Diagonal

Key Points

  • The cuboid diagonal connects two opposite corners through the interior
  • We square each dimension, sum them, then take the square root
  • This extends the 2D Pythagorean theorem to 3D space
  • The result is always longer than any single dimension

Conclusion

Finding a cuboid's diagonal uses the 3D Pythagorean theorem: ?(l² + w² + h²). This formula works for any rectangular box dimensions and gives the straight-line distance between opposite corners.

Updated on: 2026-03-15T23:19:00+05:30

280 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements