Open In App

JavaScript Program to Find Perimeter of Parallelogram

Last Updated : 22 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given the length of one side, our task is to find the perimeter of a parallelogram in JavaScript. A parallelogram is a geometric shape having four sides and its opposite sides are parallel and equal in length, and its opposite angles are also equal. The perimeter of a parallelogram is the total length of its four sides. It can be calculated by adding the lengths of two opposite sides and then multiplying the sum by 2.

Formula used

2 × (base + height)
Where,
base is horizontal side of Parallelogram
height is vertical side of Parallelogram

Table of Content

Using Function

In this approach, We will create a function that takes two parameters one is the length of one pair of opposite sides which is base and the other is the length of the other pair of opposite sides which is height. Inside the function, we will calculate the perimeter of the parallelogram using the formula: 2 × (base + height). Return the calculated perimeter value.

Example: The example below shows how to Find Perimeter of Parallelogram using Function.

JavaScript
function findPerimeter(base, height) {
    return 2 * (base + height);
}

const base = 5;
const height = 3;

const perimeter = findPerimeter(base, height);

console.log("Perimeter of parallelogram is:",
                                perimeter);

Output
Perimeter of parallelogram is: 16

Time Complexity: O(1)

Space Complexity: O(1)

Using Class

In this approach, We will define a class named Parallelogram. Inside the class, define a constructor method to initialize the base and height of the parallelogram. Define a method to calculate the perimeter using the formula 2 × (base + height). Then, we’ll create an instance of the Parallelogram class, pass the base and height as arguments to the constructor, and call the method to calculate the perimeter. Print the result.

Example: The example below shows how to Find Perimeter of Parallelogram using class.

JavaScript
// Using Class

class Parallelogram {
    constructor(base, height) {
        this.base = base;
        this.height = height;
    }

    getPerimeter() {
        return 2 * (this.base + this.height);
    }
}
const parallelogram = new Parallelogram(5, 3);
const perimeter = parallelogram.getPerimeter();
console.log("Perimeter of parallelogram is:",
                                    perimeter);

Output
Perimeter of parallelogram is: 16

Time Complexity: O(1)

Space Complexity: O(1)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads