Skip to content
the poor coder

how to declare an array in javascript

Poor Man
Published
Reading time
1 min read
On this page

How to Declare an Array in Javascript#

As a web developer, I have worked with Javascript for years and declaring an array is one of the most common tasks I perform. Here are a few ways to declare an array in Javascript:

Method 1: Using Square Brackets#

The easiest way to declare an array is by using square brackets. Here's how it works:

Text

    var myArray = []; // empty array
    var myArray2 = [1, 2, 3]; // array with elements

You can also declare an array with variables:

Text

    var name = "John";
    var age = 25;
    var myArray3 = [name, age]; // array with variables

Method 2: Using the Array() Constructor#

You can also use the Array() constructor to declare an array:

Text

    var myArray4 = new Array(); // empty array
    var myArray5 = new Array(1, 2, 3); // array with elements

You can also declare an array with a specific length:

Text

    var myArray6 = new Array(10); // array with length 10

Method 3: Using the Spread Operator#

The spread operator (...) can also be used to declare an array:

Text

    var myArray7 = [...myArray5]; // array with elements from another array (myArray5)

The spread operator can also be used to concatenate arrays:

Text

    var myArray8 = [...myArray2, ...myArray5]; // array with elements from both myArray2 and myArray5

Conclusion#

These are the three most common ways to declare an array in Javascript. Each method has its own advantages and disadvantages depending on the situation, so it's important to choose the right one for your needs.

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