How to Declare an Array With Initial Values in JavaScript

Declare an Array With Initial Values in JavaScript

In this tutorial, we'll walk through different ways to declare arrays that start out with data already inside — simple, clean, and beginner-friendly.

Method 1: Using Array Literal Syntax

This is the most common and preferred way to declare an array with initial values. It uses square brackets [] and is both readable and concise.

const fruits = ["apple", "banana", "cherry"];

console.log(fruits);
console.log("Second fruit:", fruits[1]);
["apple", "banana", "cherry"]
Second fruit: banana

Method 2: Using the Array Constructor

You can also use the new Array() constructor to create an array and pass initial values as arguments. Although not as widely used as literals, it’s useful to know — especially when working with dynamic data or integrating into class-based patterns.

const items = new Array("Item 1", "Item 2", "Item 3");

console.log(items);
["Item 1", "Item 2", "Item 3"]

Method 3: Using Array.of()

Array.of() is another way to create arrays, especially when you want to ensure each argument is treated as a distinct item — even single numbers. This method avoids confusion that can happen with the Array constructor when passing numeric values.

const scores = Array.of(100, 90, 80);

console.log(scores);
console.log("Total scores:", scores.length);
[100, 90, 80]
Total scores: 3

Method 4: Declaring and Assigning Initial Values Later

You might want to declare an array first and assign values later. This gives you flexibility in larger programs or conditional logic. While it's technically not initializing with values at the moment of declaration, it's still a common pattern when you're planning ahead.

let tasks;

tasks = ["Clean", "Cook", "Read"];

console.log(tasks);
["Clean", "Cook", "Read"]

When to Use Each Method

The array literal syntax is almost always the best choice — it's short, readable, and intuitive. The constructor method or Array.of() may be appropriate in special cases where you're dynamically generating arrays or dealing with types. Declaring first and assigning later is useful when the values aren’t known up front or depend on logic elsewhere in your program.

Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...