Calculate the area of a rectangle using JavaScript

Before we write any code, let's define our problem and break it down into steps. The formula to calculate the area of a rectangle is length times width.

Depiction of rectangle area formula
Depiction of rectangle area formula

Steps

  1. Define a function and pass length and width to it as parameters.

  2. Calculate the area in the defined function.

  3. Return the calculated area.

Code example

Let's run the following widget to calculate the area of the rectangle.

Calculating the area of the rectangle

Note: Please scroll down in the output tab to see the calculated area.

Code explanation

HTML file: We add two input fields to get the length and width of the user. Additionally, a button has been added, which is triggered by the user to invoke the area function.

JavaScript file:

  • Line 1: We define a area function and list the parameter length and width inside the parathesis of this function.

  • Line 2: We calculate the area and store it into result variable.

  • Line 3: We write the value of result variable in the element that has ID output to display the output on the screen.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved