Surface area of Cube using JavaScript
Last Updated :
14 Mar, 2024
A cube is a 3-dimensional box-like figure represented in the 3-dimensional plane that has six-shaped faces. It has length, width, and height of the same dimension. Three sides of a cube meet at the same vertex.
We can find the Surface area of Cube in JavaScript by using different ways including, the JavasScript function, Arrow function, and by using class.
Using JavaScript Function
We will create a function that will hold the formula by taking the edge of a cube (a) as a parameter. The function proceeds to calculate the Surface area of the Cube using the formula (6 * a * a). The calculated Surface Area is returned as the result of the function.
Syntax
function surfaceAreaCube(a) {
return 6 * a * a;
}
Example: Below is the function to find the Surface area of the Cube
Javascript
function surfaceAreaCube(a) {
return (6 * a * a);
}
let a = 10;
console.log('Surface area = ' + surfaceAreaCube(a));
Output:
Surface area = 600
Using Arrow function
ES6 Arrow functions enable us to write functions with simpler and shorter syntax. We can utilize this function that will return the Surface area of a Cube. First, we will define a function and pass a (edge) as an argument. we will write the mathematical expression that will return the Surface area of a cube. Finally, we will call the function.
Syntax
surfaceAreaCube = (a) => {
return(6 * a * a)
}
Example: Below is the function to find the Surface area of the Cube:
Javascript
surfaceAreaCube = (a) => {
return (6 * a * a)
}
let a = 10;
console.log('Surface area = ' + surfaceAreaCube(a));
Output:
Surface area = 600
Using class
Classes are similar to functions. Here, a class keyword is used instead of a function keyword. Unlike functions classes in JavaScript are not hoisted. The constructor method in JavaScript is a special method used for initializing objects created with a class. We need to pass the edge (a) as a parameter that will hold the surface area calculated as 6 * a * a. Finally, we will create an object for the class and pass the value (a).
Syntax
class SurfaceArea {
constructor(a) {
this.surfaceArea = 6 * a * a;
}
}
Example: Below is the function to find the Surface area of the Cube
Javascript
class SurfaceArea {
constructor(a) {
this.surfaceArea = 6 * a * a;
}
}
const cube = new SurfaceArea(10);
console.log('Surface area = ' + cube.surfaceArea);
Output:
Surface area = 600
Time complexity: O(1), as the execution time is constant and does not grow with the size of the input.
Auxiliary Space complexity: O(1) as it uses a constant amount of memory regardless of the input size.
Share your thoughts in the comments
Please Login to comment...