JavaScript Program to Find Perimeter of Square
Given the length of one side, our task is to find the perimeter of a square in JavaScript. The perimeter of a square is the total length of its four sides. It can be calculated by multiplying the length of one side by 4 and all its angles measure 90 degrees.
Example:
Formula for calculating Perimeter of Square is: 4*s Where, s is sides of a square Input: 4 Output: 16
Use the below approaches to find the Perimeter of the Square:
Table of Content
- Using Function
- Using Class
Using Function
In this approach, We will create a function that takes one parameter, the side of the square. Inside the function, calculate the perimeter of the square by multiplying the side length by 4 (as all sides of the square are equal). Return the calculated perimeter value.
Example: The example below shows the demonstration of finding the perimeter of the square using the function
function findPerimeter(side) {
return 4 * side;
}
const sideLength = 4;
// Call the function
const perimeter = findPerimeter(sideLength);
console.log("Perimeter of square is :",
perimeter);
Output
Perimeter of square is : 16
Time complexity: O(1)
Space complexity: O(1)
Using Class
In this approach, define a class named Square. Within the class, a constructor method is defined to initialize the side length of the square. Additionally, a method is defined to calculate the perimeter of the square using the formula 4 * side. To utilize this class, an instance of Square is created by passing the side length as an argument to the constructor. Finally, the method for calculating the perimeter is called on the instance, and the result is printed.
Example: The example below shows the demonstration of finding perimeter of square using class.
class Square {
// Constructor method
constructor(side) {
this.side = side;
}
getPerimeter() {
return 4 * this.side;
}
}
// Create an instance of Square
const square = new Square(4);
const perimeter = square.getPerimeter();
console.log("Perimeter of square is :", perimeter);
Output
Perimeter of square is : 16
Time Complexity: O(1)
Space Complexity: O(1)