The area of a rectangle is the region enclosed by its all four side that is calculated by multiplying the height and width dimensions together.
The perimeter of rectangle is the sum of the areas of its sides. To find the area, use the simple formula A = w*h. where w is width of rectangle and h is height of rectangle. To find the perimeter, use the formula 2 * (w+h).
This example demonstrates how to calculate the area and parameter of rectangles using JavaScript.
You can use the below JavaScript code to find the area and parameter of a rectangle. First, we read the value of given width and height by the user in the width and height variables. Next, we use the width * height formula to calculate the area of the rectangle. After that, we calculate perimeter of the rectangle using the 2 * (width of rectangle + height of rectangle). Finally, we display the values of area and perimeter into the input controls.
How to calculate area of circle in JavaScript
<html> <head> <title>Calculate the area and parimeter of a rectangle in javascript</title> <script language="JavaScript"> function CalculateArea() { let width = document.form1.txtWidth.valueAsNumber; let height = document.form1.txtHeight.valueAsNumber; document.form1.txtArea.value = width * height; document.form1.txtParameter.value = 2 * ( width + height); } </script> </head> <body> <form name="form1"> <div> Enter the <b>Width</b> of rectangle: <input type="number" name="txtWidth" onChange='CalculateArea();' /> </div> <div> Enter the <b>Height</b> of rectangle: <input type="number" name="txtHeight" onChange='CalculateArea();' /> </div> <div> <input type="button" value="Calculate" onClick='CalculateArea();' /> </div> <div> The<b>area</b> of the rectanle is <input type="number" name="txtArea" length="10" /> </div> <div> The<b>parameter</b> of the rectanle is <input type="number" name="txtParameter" length="10" /> </div> </form> </body> </html>
If you are using input html element with type=number
to read the width and height, you should use the ‘valueAsNumber’ property to read the value of html input elements. If you use the ‘value’ property, then you have to cast the value of input html elements into the number like this:
let val = document.form1.txtWidth.value;
let width = Number(val);