Area and Perimeter of Rectangle

Program to calculate area and perimeter of a rectangle

BeginnerTopic: Basic Programs
Back

JavaScript Area and Perimeter of Rectangle Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// 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

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

Measured in square units
Represents the space inside the rectangle

2.

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:

function rectangleArea(length, width) {
}

function rectanglePerimeter(length, width) {

    return 2 * (length + width);
}
    return length * width;

Benefits:

Reusable functions
Clear separation of concerns
Easy to test
Can be used independently

Related Shapes

Square

(special rectangle where length = width):

function squareArea(side) {
}

function squarePerimeter(side) {

    return 4 * side;
}
    return side * side; // or side ** 2

Real-world Applications

Flooring calculations
Fencing requirements
Painting area calculations
Land area measurements
Construction planning

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.

Table of Contents