How to Create Array in JavaScript: Syntax and Examples
In JavaScript, you can create an array using the
Array constructor or by using square brackets []. The square bracket syntax is the most common and simple way to create an array with elements inside.Syntax
You can create an array in JavaScript in two main ways:
- Using square brackets: This is the simplest way to create an array with elements.
- Using the Array constructor: This creates an array object, optionally with a specified length or elements.
javascript
const array1 = ['element1', 'element2', 'element3']; const array2 = new Array('element1', 'element2', 'element3'); const emptyArray = [];
Example
This example shows how to create arrays using both methods and how to access elements.
javascript
const fruits = ['apple', 'banana', 'cherry']; console.log(fruits[0]); // apple const numbers = new Array(1, 2, 3); console.log(numbers[2]); // 3 const empty = []; console.log(empty.length); // 0
Output
apple
3
0
Common Pitfalls
One common mistake is using the Array constructor with a single number, which creates an empty array of that length instead of an array with that number as an element.
For example, new Array(3) creates an empty array with length 3, not an array containing the number 3.
javascript
const wrong = new Array(3); console.log(wrong.length); // 3 console.log(wrong); // [ <3 empty items> ] const right = [3]; console.log(right.length); // 1 console.log(right); // [3]
Output
3
[ <3 empty items> ]
1
[3]
Quick Reference
| Method | Description | Example |
|---|---|---|
| Square Brackets | Create array with elements | const arr = [1, 2, 3]; |
| Array Constructor | Create array with elements or length | const arr = new Array(1, 2, 3); |
| Array Constructor with single number | Creates empty array of that length | const arr = new Array(5); |
Key Takeaways
Use square brackets [] to create arrays easily with elements.
The Array constructor can create arrays but behaves differently with a single number.
Access array elements by their index starting at 0.
Empty arrays have a length of 0 and contain no elements.
Avoid using new Array(number) unless you want an empty array of that length.