Area and Perimeter of Rectangle
Program to calculate area and perimeter of a rectangle
JavaScript Area and Perimeter of Rectangle Program
This program helps you to learn the fundamental structure and syntax of JavaScript programming.
// 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`);Rectangle Dimensions: Length: 10 Width: 5 Area: 50 square units Perimeter: 30 units Using functions: Area: 48 sq units Perimeter: 28 units
Understanding Area and Perimeter of Rectangle
This program calculates the area and perimeter of a rectangle using geometric formulas.
Rectangle Formulas
1.
Area
: length × width
2.
Perimeter
: 2 × (length + width)
Example Calculation
For a rectangle with length = 10 and width = 5:
Function Approach
Creating separate functions for each calculation:
function rectangleArea(length, width) {
}
function rectanglePerimeter(length, width) {
return 2 * (length + width);
}
return length * width;Benefits:
Related Shapes
Square
(special rectangle where length = width):
function squareArea(side) {
}
function squarePerimeter(side) {
return 4 * side;
}
return side * side; // or side ** 2Real-world Applications
Input Validation
Always validate inputs:
function rectangleArea(length, width) {
if (length <= 0 || width <= 0) {
}
return length * width;
}
return "Invalid dimensions";Let us now understand every line and the components of the above program.
Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.