Area and Perimeter of Rectangle in JavaScript

area = l*w. perimeter = 2*(l+w). Height is not a diagonal.

BeginnerBasic ProgramsExample 10 of 10
area-and-perimeter-of-rectangle.js
1// Formula: Area = length × width
2// Formula: Perimeter = 2 × (length + width)
3
4let length = 10;
5let width = 5;
6
7let area = length * width;
8let perimeter = 2 * (length + width);
9
10console.log("Rectangle Dimensions:");
11console.log("Length:", length);
12console.log("Width:", width);
13console.log("Area:", area, "square units");
14console.log("Perimeter:", perimeter, "units");
15
16// Function version
17function rectangleArea(length, width) {
18 return length * width;
19}
20
21function rectanglePerimeter(length, width) {
22 return 2 * (length + width);
23}
24
25let rectLength = 8;
26let rectWidth = 6;
27
28console.log("\nUsing functions:");
29console.log(`Area: ${rectangleArea(rectLength, rectWidth)} sq units`);
30console.log(`Perimeter: ${rectanglePerimeter(rectLength, rectWidth)} units`);

Output

Rectangle Dimensions:
Length: 10
Width: 5
Area: 50 square units
Perimeter: 30 units

Using functions:
Area: 48 sq units
Perimeter: 28 units

What's going on

Area is multiply. Perimeter is the walk around. Mix them up and the number is still a number.

Negative length should be rejected. The formula will not save you.