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.
Steps
Define a function and pass length and width to it as parameters.
Calculate the area in the defined function.
Return the calculated area.
Code example
Let's run the following widget to calculate 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
areafunction and list the parameter length and width inside the parathesis of this function.Line 2: We calculate the area and store it into
resultvariable.Line 3: We write the value of
resultvariable in the element that has IDoutputto display the output on the screen.
Free Resources