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 create a zero-filled JavaScript array?
To create a zero-filled JavaScript array, you have several methods available. The most common approaches include using Array.fill(), Array.from(), or typed arrays like Uint8Array.
Using Array.fill() Method
The Array.fill() method is the most straightforward way to create a zero-filled array:
<html>
<body>
<script>
// Create array of length 5 filled with zeros
var zeroArray = new Array(5).fill(0);
document.write("Zero-filled array: " + zeroArray);
// Alternative syntax
var anotherArray = Array(3).fill(0);
document.write("<br>Another zero array: " + anotherArray);
</script>
</body>
</html>
Zero-filled array: 0,0,0,0,0 Another zero array: 0,0,0
Using Array.from() Method
The Array.from() method provides more flexibility for creating arrays:
<html>
<body>
<script>
// Create zero-filled array using Array.from()
var zeroArray = Array.from({length: 4}, () => 0);
document.write("Array.from() result: " + zeroArray);
// Using Array.from() with fill method
var simpleZeros = Array.from(Array(3), () => 0);
document.write("<br>Simple zeros: " + simpleZeros);
</script>
</body>
</html>
Array.from() result: 0,0,0,0 Simple zeros: 0,0,0
Using Typed Arrays
Typed arrays like Uint8Array automatically initialize with zeros:
<html>
<body>
<script>
var normalArray = ["marketing", "technical", "finance", "sales"];
var zeroFilledArray = new Uint8Array(4);
document.write("Normal array: " + normalArray);
document.write("<br>Zero filled array: " + zeroFilledArray);
document.write("<br>Array length: " + zeroFilledArray.length);
</script>
</body>
</html>
Normal array: marketing,technical,finance,sales Zero filled array: 0,0,0,0 Array length: 4
Comparison of Methods
| Method | Syntax | Performance | Use Case |
|---|---|---|---|
Array.fill() |
new Array(n).fill(0) |
Good | General purpose |
Array.from() |
Array.from({length: n}, () => 0) |
Good | More flexible |
Uint8Array |
new Uint8Array(n) |
Best | Numeric data only |
Conclusion
Use Array.fill(0) for most cases as it's readable and flexible. Choose Uint8Array for performance-critical numeric operations where you need guaranteed zero initialization.
Advertisements
