JavaScript
// Formula: Area = length × width
// Formula: Perimeter = 2 × (length + width)
let length = 10;
let width = 5;
let area = length * width;
let perimeter = 2 * (length + width);
console.log("Rectangle Dimensions:");
console.log("Length:", length);
console.log("Width:", width);
console.log("Area:", area, "square units");
console.log("Perimeter:", perimeter, "units");
// Function version
function rectangleArea(length, width) {
return length * width;
}
function rectanglePerimeter(length, width) {
return 2 * (length + width);
}
let rectLength = 8;
let rectWidth = 6;
console.log("\nUsing functions:");
console.log(`Area: ${rectangleArea(rectLength, rectWidth)} sq units`);
console.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
This program calculates the area and perimeter of a rectangle using geometric formulas.
Rectangle Formulas
-
Area: length × width
- Measured in square units
- Represents the space inside the rectangle
-
Perimeter: 2 × (length + width)
- Measured in linear units
- Represents the total distance around the rectangle
Example Calculation
For a rectangle with length = 10 and width = 5:
- Area = 10 × 5 = 50 square units
- Perimeter = 2 × (10 + 5) = 2 × 15 = 30 units
Function Approach
Creating separate functions for each calculation:
javascriptfunction rectangleArea(length, width) { return length * width; } function rectanglePerimeter(length, width) { return 2 * (length + width); }
Benefits:
- Reusable functions
- Clear separation of concerns
- Easy to test
- Can be used independently
Related Shapes
Square (special rectangle where length = width):
javascriptfunction squareArea(side) { return side * side; // or side ** 2 } function squarePerimeter(side) { return 4 * side; }
Real-world Applications
- Flooring calculations
- Fencing requirements
- Painting area calculations
- Land area measurements
- Construction planning
Input Validation
Always validate inputs:
javascriptfunction rectangleArea(length, width) { if (length <= 0 || width <= 0) { return "Invalid dimensions"; } return length * width; }