# JavaScript program to find Area and Perimeter of Rectangle

We are writing a JavaScript program to calculate the area and perimeter of a rectangle. The program will prompt the user to input the width and length of the rectangle, and then we will use these values to calculate the area and perimeter. We will be continuously using these formulas: area = width * length, and perimeter = 2 * (width + length) to find the desired measurements.

## Approach

The approach to find the Area and Perimeter of a rectangle in JavaScript can be done as follows −

• Define the length and width of the rectangle using variables.

• Calculate the Area by multiplying the length and width of the rectangle.

• Calculate the Perimeter by adding the twice the length and twice the width of the rectangle.

• Display the result of both Area and Perimeter.

• Store the result in variables and return the values if needed.

• Repeat the above steps for different sets of length and width as required.

## Example

Here is an example of a JavaScript program that calculates the area and perimeter of a rectangle −

// Function to find the area of a rectangle
function findArea(width, height) {
return width * height;
}
// Function to find the perimeter of a rectangle
function findPerimeter(width, height) {
return 2 * (width + height);
}

// Input for width and height
var width = 5;
var height = 10;

// Calculate the area and perimeter
var area = findArea(width, height);
var perimeter = findPerimeter(width, height);

// Output the results
console.log("Area of rectangle: " + area);
console.log("Perimeter of rectangle: " + perimeter);

## Explanation

• First, two functions are defined - findArea and findPerimeter to calculate the area and perimeter of the rectangle, respectively.

• The findArea function takes two arguments - width and height and returns the result of width * height.

• The findPerimeter function takes two arguments - width and height and returns the result of 2 * (width + height).

• The width and height of the rectangle are defined with var width = 5 and var height = 10.

• The area and perimeter of the rectangle are calculated using the findArea and findPerimeter functions and stored in the variables area and perimeter.

• Finally, the results are output to the console using console.log and displayed in the format "Area of rectangle: X" and "Perimeter of rectangle: Y", where X is the area and Y is the perimeter.

Updated on: 21-Jun-2024

5K+ Views