Skip to content
the poor coder

declare array in javascript

Poor Man
Published
Reading time
1 min read
On this page

How to declare an array in JavaScript?#

Arrays are a type of variable in JavaScript that allow you to store multiple values in a single variable. This can be useful for organizing data and making it easier to access and manipulate.

Declaring an array using square brackets []#

The simplest way to declare an array in JavaScript is by using square brackets []. Here is an example:

Text
var myArray = [1, 2, 3, 4, 5];

This creates a new variable called myArray that contains five values: 1, 2, 3, 4, and 5. You can access individual elements of the array using their index, which starts at 0. For example:

Text
console.log(myArray[0]); /* Output: 1 */
console.log(myArray[2]); /* Output: 3 */

Declaring an array using the Array() constructor#

You can also declare an array in JavaScript using the Array() constructor. Here is an example:

Text
var myArray = new Array(1, 2, 3, 4, 5);

This does the same thing as the previous example, creating a new variable called myArray that contains five values. However, some developers prefer to use the constructor syntax because it can be more clear and explicit.

Declaring an empty array#

Sometimes you may want to declare an array without any initial values. You can do this by using either the empty square bracket syntax or the Array() constructor with no arguments. Here are some examples:

Text
var myEmptyArray1 = [];
var myEmptyArray2 = new Array();

Both of these examples create a new variable with an empty array. You can add values to this array later by using the push() method or by assigning values to specific indexes.

Conclusion#

Declaring an array in JavaScript is a simple task that can be done using square brackets or the Array() constructor. Whether you choose to use one method or the other is largely a matter of personal preference, but it's important to understand both options in case you encounter code that uses one or the other.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC