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 arrays in JavaScript?
JavaScript provides multiple ways to create arrays. Arrays are used to store multiple values in a single variable and can hold different data types.
Using Array Literal (Recommended)
The most common and recommended way to create arrays is using square brackets:
<html>
<head>
<title>Array Literal Example</title>
</head>
<body>
<script>
var animals = ["Dog", "Cat", "Tiger"];
var numbers = [1, 2, 3, 4, 5];
var mixed = ["Apple", 10, true, null];
console.log("Animals:", animals);
console.log("Numbers:", numbers);
console.log("Mixed array:", mixed);
</script>
</body>
</html>
Animals: ["Dog", "Cat", "Tiger"] Numbers: [1, 2, 3, 4, 5] Mixed array: ["Apple", 10, true, null]
Using Array Constructor
You can also create arrays using the new Array() constructor:
<html>
<head>
<title>Array Constructor Example</title>
</head>
<body>
<script>
var animals = new Array("Dog", "Cat", "Tiger");
var emptyArray = new Array(5); // Creates array with 5 empty slots
var singleElement = new Array("Hello");
console.log("Animals:", animals);
console.log("Empty array length:", emptyArray.length);
console.log("Single element:", singleElement);
</script>
</body>
</html>
Animals: ["Dog", "Cat", "Tiger"] Empty array length: 5 Single element: ["Hello"]
Creating Empty Arrays
You can create empty arrays and populate them later:
<html>
<head>
<title>Empty Array Example</title>
</head>
<body>
<script>
var fruits = [];
fruits[0] = "Apple";
fruits[1] = "Banana";
fruits.push("Orange");
console.log("Fruits array:", fruits);
console.log("Array length:", fruits.length);
</script>
</body>
</html>
Fruits array: ["Apple", "Banana", "Orange"] Array length: 3
Key Points
- Array literal
[]is preferred overnew Array() - Arrays can store different data types in the same array
- When using
new Array()with a single number, it creates an array with that length - Maximum array length is 4,294,967,295
- Array indices start from 0
Comparison
| Method | Syntax | Performance | Recommendation |
|---|---|---|---|
| Array Literal | [] |
Faster | Recommended |
| Array Constructor | new Array() |
Slightly slower | Use when needed |
Conclusion
Use array literals [] for creating arrays as they are more readable and performant. The new Array() constructor is useful when you need to create arrays with a specific initial length.
Advertisements
