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 × width2// Formula: Perimeter = 2 × (length + width)34let length = 10;5let width = 5;67let area = length * width;8let perimeter = 2 * (length + width);910console.log("Rectangle Dimensions:");11console.log("Length:", length);12console.log("Width:", width);13console.log("Area:", area, "square units");14console.log("Perimeter:", perimeter, "units");1516// Function version17function rectangleArea(length, width) {18 return length * width;19}2021function rectanglePerimeter(length, width) {22 return 2 * (length + width);23}2425let rectLength = 8;26let rectWidth = 6;2728console.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.