JavaScript Arrays: A Beginner’s Guide with Examples

Published: (February 26, 2026 at 01:36 PM EST)
3 min read
Source: Dev.to

Source: Dev.to

What Is an Array?

Arrays store multiple values in a single variable. They use zero‑based indexing, meaning the first element is at index 0.

let arr = [10, 20, 30];

// Indexes
// 10 → index 0
// 20 → index 1
// 30 → index 2

Different Ways to Create an Array

Using Array Literal (Most Common Method)

let arr = [1, 2, 3];

Using the Array Constructor

Create an array with specific elements:

let arr = new Array(1, 2, 3); // [1, 2, 3]

Create an empty array of a specified length (creates empty slots, not undefined values):

let arr = new Array(4); // length 4, sparse array

Key difference:
new Array(5) → array with 5 empty slots.
[5] → array containing the single number 5.

Creating an Empty Array

let arr = [];

arr[0] = 10;
arr.push(20);

Using Array.of()

let arr = Array.of(1, 2, 3);
let arr1 = Array.of(3);

console.log(arr);   // [1, 2, 3]
console.log(arr1);  // [3]

Using Array.from()

Example 1 – from a string

let str = "Apple";
let arr = Array.from(str);
console.log(arr); // ["A", "P", "P", "L", "E"]

Example 2 – from an object with a length property

let arr = Array.from({ length: 5 });
console.log(arr); // [undefined, undefined, undefined, undefined, undefined]

Using the Spread Operator

Copying an array (shallow copy)

let a = [1, 2, 3];
let b = [...a];
console.log(b); // [1, 2, 3]

Merging arrays

let a = [1, 2];
let b = [3, 4];
let c = [...a, ...b];
console.log(c); // [1, 2, 3, 4]

Accessing Array Elements

Array indexes always start at 0.

let fruits = ["apple", "orange", "guava", "grapes"];

console.log(fruits[0]); // "apple"
console.log(fruits[1]); // "orange"

Accessing the last element

console.log(fruits[fruits.length - 1]); // "grapes"

length gives the total number of elements; the last index is length - 1.

Updating Array Elements

Arrays are mutable, so you can change values directly.

Single element update

fruits[1] = "Banana";
console.log(fruits); // ["apple", "Banana", "guava", "grapes"]

Updating all elements with a loop

for (let i = 0; i  {
  fruits[index] = value.toUpperCase();
});

Conclusion

Arrays are a fundamental part of JavaScript, enabling efficient storage and manipulation of multiple values. Mastering array creation, access, and updates is essential for building real‑world applications.

0 views
Back to Blog

Related posts

Read more »

Array Methods You Must Know

Mutating Methods Change Original Array - push – Add to end - pop – Remove from end - shift – Remove from start - unshift – Add to start All of these do not ret...