JavaScript: Find the Perimeter of a Rectangle

1. Introduction

The perimeter of a geometric shape is the length of its outer boundary. Specifically, for a rectangle, the perimeter is calculated by summing up all its four sides. In this guide, we'll create a JavaScript program to determine the perimeter of a rectangle based on its length and width.

2. Program Overview

During this tutorial, we will:

1. Specify the length and width of the rectangle.

2. Develop a function to calculate the perimeter using the given dimensions.

3. Showcase the computed perimeter.

3. Code Program

let length = 10;  // Length of the rectangle
let width = 5;   // Width of the rectangle
let perimeter;   // Variable to store the perimeter of the rectangle

// Function to determine the perimeter of a rectangle
function findPerimeter(l, w) {
    return 2 * (l + w);
}

perimeter = findPerimeter(length, width);

console.log("The perimeter of a rectangle with length " + length + " units and width " + width + " units is: " + perimeter + " units.");

Output:

The perimeter of a rectangle with length 10 units and width 5 units is: 30 units.

4. Step By Step Explanation

1. Variable Declaration: We start by specifying the length and width of the rectangle. Additionally, a variable perimeter is initialized to hold the outcome.

2. Perimeter Calculation Function: The findPerimeter(l, w) function carries out the perimeter calculation using the formula provided. We multiply the sum of the rectangle's length and width by 2 to get the total perimeter.

3. Calculating the Perimeter: We call our findPerimeter function with the given length and width, and the resulting value is stored in the perimeter variable.

4. Result Display: Using console.log, we then showcase the dimensions of the rectangle along with its computed perimeter.

Comments