Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Volume difference of cuboids in JavaScript
We are required to write a JavaScript function that takes in two arrays, specifying the lengths, widths, and heights of two cuboids.
Our function should calculate the volume of both cuboids and return their absolute difference.
Formula
The volume of a cuboid is calculated as:
Volume = length × width × height
Example
Following is the code:
const h1 = 10;
const w1 = 12;
const l1 = 15;
const h2 = 12;
const w2 = 15;
const l2 = 9;
const findVolumeDifference = (l1, w1, h1, l2, w2, h2) => {
const v1 = l1 * w1 * h1;
const v2 = l2 * w2 * h2;
const diff = Math.abs(v1 - v2);
return diff;
};
console.log("Cuboid 1 volume:", l1 * w1 * h1);
console.log("Cuboid 2 volume:", l2 * w2 * h2);
console.log("Volume difference:", findVolumeDifference(l1, w1, h1, l2, w2, h2));
Output
Cuboid 1 volume: 1800 Cuboid 2 volume: 1620 Volume difference: 180
Using Arrays as Parameters
As mentioned in the problem statement, we can also accept arrays containing the dimensions:
const cuboid1 = [15, 12, 10]; // [length, width, height]
const cuboid2 = [9, 15, 12];
const findVolumeDifferenceFromArrays = (cuboid1, cuboid2) => {
const v1 = cuboid1[0] * cuboid1[1] * cuboid1[2];
const v2 = cuboid2[0] * cuboid2[1] * cuboid2[2];
return Math.abs(v1 - v2);
};
console.log("Volume difference:", findVolumeDifferenceFromArrays(cuboid1, cuboid2));
Output
Volume difference: 180
Key Points
- Volume of cuboid = length × width × height
- Use
Math.abs()to get absolute difference - Parameters can be passed individually or as arrays
- Order of dimensions doesn't affect the volume calculation
Conclusion
This function efficiently calculates the volume difference between two cuboids using the basic volume formula and JavaScript's Math.abs() method for absolute difference.
Advertisements
