Home>Article>Web Front-end> JavaScript program to find the area and perimeter of a rectangle
We are writing a JavaScript program to calculate the area and perimeter of a rectangle. The program will prompt the user to enter the width and length of the rectangle, and we will then use these values to calculate the area and perimeter. We will keep using these formulas: Area = Width * Length and Perimeter = 2 * (Width Length) to find the desired measurements.
The method to find the area and perimeter of a rectangle in JavaScript can be done as follows -
Use variables to define the length and width of the rectangle.
Calculate the area by multiplying the length and width of the rectangle.
Calculate the perimeter by adding twice the length and twice the width of the rectangle.
Display results for area and perimeter.
Store the result in a variable and return the value when needed.
Repeat the above steps for different length and width groups as needed.
This 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);
First define two functions -findAreaandfindPerimeterto calculate the area and perimeter of the rectangle respectively.
findAreaThe function takes two parameters -widthandheightand returns the result ofwidth * height.
findPerimeterThe function takes two parameters -widthandheightand returns2 * (width height).
The width and height of the rectangle are defined byvar width = 5andvar height = 10.
The area and perimeter of a rectangle are calculated using thefindAreaandfindPerimeterfunctions and stored in the variablesareaand perimeter.
Finally, useconsole.logto output the results to the console and display them in the format of "Rectangle Area: X" and "Rectangle Perimeter: Y", where X is the area, Y is the perimeter.
The above is the detailed content of JavaScript program to find the area and perimeter of a rectangle. For more information, please follow other related articles on the PHP Chinese website!