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
How to execute a cube of numbers of a given array in JavaScript?
To calculate the cube of each number in an array, you can use several approaches. The most common methods involve iterating through the array and applying the cube operation (n³) to each element.
Using a for Loop
The traditional approach uses a for loop to iterate through the array and replace each element with its cube:
<html>
<body>
<script>
var numbers = [1, 2, 3, 4, 5];
// Calculate cube of each element
for (var i = 0; i < numbers.length; i++) {
numbers[i] = numbers[i] * numbers[i] * numbers[i];
}
document.write("Cubes: " + numbers);
</script>
</body>
</html>
Cubes: 1,8,27,64,125
Using Math.pow() Method
You can also use the Math.pow() function for cleaner code:
<html>
<body>
<script>
var numbers = [2, 3, 4, 5, 6];
for (var i = 0; i < numbers.length; i++) {
numbers[i] = Math.pow(numbers[i], 3);
}
document.write("Cubes using Math.pow(): " + numbers);
</script>
</body>
</html>
Cubes using Math.pow(): 8,27,64,125,216
Using Array.map() Method
For a functional programming approach, use map() to create a new array with cubed values:
<html>
<body>
<script>
var numbers = [1, 2, 3, 4, 5];
// Create new array with cubed values
var cubes = numbers.map(function(num) {
return num * num * num;
});
document.write("Original: " + numbers + "<br>");
document.write("Cubes: " + cubes);
</script>
</body>
</html>
Original: 1,2,3,4,5 Cubes: 1,8,27,64,125
Comparison of Methods
| Method | Modifies Original | Readability | Best For |
|---|---|---|---|
| for loop | Yes | Good | In-place modification |
| Math.pow() | Yes | Better | Any power operation |
| Array.map() | No | Best | Functional programming |
Working with Decimal Numbers
These methods also work with decimal numbers:
<html>
<body>
<script>
var decimals = [1.5, 2.5, 3.5];
var cubes = decimals.map(function(num) {
return Math.pow(num, 3);
});
document.write("Decimal cubes: " + cubes);
</script>
</body>
</html>
Decimal cubes: 3.375,15.625,42.875
Conclusion
Use the for loop for in-place modification, Math.pow() for clarity, or Array.map() when you need to preserve the original array. All methods effectively calculate cubes of array elements.
Advertisements
