Skip to main content

Command Palette

Search for a command to run...

The Ultimate Guide to JavaScript Arrays for Beginners

Published
•9 min read
The Ultimate Guide to JavaScript Arrays for Beginners

You are trying to make a personlised music app, adding your favourite songs in a playlist. You have no idea about arrays. So, you would store your songs like:

let song1 = "Blinding Lights";
let song2 = "As It Was";
let song3 = "Starboy";
let song4 = "In The End";
let song5 = "Lucid Dreams";
// does not scale

But, your playlist will not end at these five songs. You would want to continue adding to the list. This process your become taxing. You would want to do the same thing in an easier form, which is what Array helps us to do.

An array is a single variable that holds an ordered list of values. N number of songs in one playlist.

The Array object enables storing a collection of multiple items under a single variable name.

Now, your playlist will turn out like:

const playlist = [
  "Blinding Lights",
  "As It Was",
  "Starboy",
  "In The End",
  "Lucid Dreams"
];

How to Create an Array

There are two ways to create an Array:

// Array literal, mostly use this
const playlist = ["Blinding Lights", "Lucid Dreams", "Starboy"];

// Empty array to fill it later
const queue = [];

// Numbers like leaderboard scores
const scores = [4200, 3100, 5800, 2750];

// Booleans like which accounts have logged in
const hasLoggedIn = [true, false, true, true];

// Mixed types work but are usually a bad idea
const messy = ["Drake", 42, true, null];

// Array constructor but avoid
const trap = new Array(3); // 3 empty slots, NOT the number 3

Arrays must hold values of the same type. Mixing strings, numbers, and booleans in one array makes code unpredictable. Keep arrays consistent by adding values of one type only.

💡
new Array(3) does NOT create an array containing 3. It creates an array with 3 empty slots — [<3 empty items>]. Just use [].

Accessing Array Elements

Every slot in an array has a position number called an index. The single most important rule:

The first element is at index 0, not 1.

Consider your spotify playlist:

Use square bracket notation [index] to read any element:

const playlist = ["Blinding Lights", "As It Was", "Starboy", "In The End", "Lucid Dreams"];

// song at index 0 i.e. first song
console.log(playlist[0]); // Blinding Lights
// song at index 2
console.log(playlist[2]); // Starboy   
// song at index 4
console.log(playlist[4]); // Lucid Dreams     

// No song here because out of range
console.log(playlist[5]); // undefined

// Get the last song 
console.log(playlist[playlist.length - 1]); // Lucid Dreams  
💡
Recently, JavaScript added array.at(-1) to get the last element cleanly. playlist.at(-1) returns "Lucid Dreams" , playlist.at(-2) returns "In The End".

Updating Array Elements

Arrays are mutable. Unlike strings, you can change any value in place. Use the same bracket notation to write instead of read:

const playlist = ["Blinding Lights", "As It Was", "Starboy", "In The End", "Lucid Dreams"];


console.log(playlist);
// ['Blinding Lights', 'As It Was', 'Starboy', 'In The End', 'Lucid Dreams']

// Swap the second song (index 1)
playlist[1] = "Flowers";

console.log(playlist);
// ['Blinding Lights', 'Flowers', 'Starboy', 'In The End', 'Lucid Dreams']

// Add a new song at the next position
playlist[5] = "Cruel Summer";

console.log(playlist);
// ['Blinding Lights', 'Flowers', 'Starboy', 'In The End', 'Lucid Dreams', 'Cruel Summer']
💡
If your array has 5 items and you write playlist[10] = "Espresso", JavaScript creates empty holes at positions 5–9. Those holes behave inconsistently in loops and comparisons and are very hard to debug. Never skip indices. To safely add to the end, use array.push()

The .length Property

.length is built into every array. It returns the count of elements. Do not add parentheses as it is a property, not a method.

const notifications = [
  "@drake liked your post",
  "New follower: taylorswift",
  "You were tagged in a reel"
];

console.log(notifications.length);    // 3
console.log(notifications.length());   // TypeError: notifications.length is not a function

// .length updates automatically when you change the array
notifications[3] = "New comment on your video";
console.log(notifications.length);    // 4

// Get the latest notification without hardcoding
const latest = notifications[notifications.length - 1];
console.log(latest); // "New comment on your video"

Looping of Array: Visiting Every Element

Looping Statements Makes it feasible to visit every element of the array. We dont need to visit every index manually.

For Loop

Use this when you need the index of each element (e.g., track numbers, rankings).

const mostListened = ["Starboy", "In The End", "Blinding Lights"];

for (let i = 0; i < mostListened.length; i++) {
  console.log("#" + (i + 1) + " " + mostListened[i]);
}
// #1 Starboy
// #2 In The End
// #3 Blinding Lights

How it works: let i = 0 starts at the first index. i < mostListened.length keeps going while there are elements in array. i++ goes to the next position each iteration.

For...Of

Use this when you only need the value, not the index. Cleaner and less error-prone.

const playlist = ["Blinding Lights", "As It Was", "Starboy"];

for (let song of playlist) {
  console.log("Now playing: " + song);
}
// Now playing: Blinding Lights
// Now playing: As It Was
// Now playing: Starboy

Another example:

const userListeningHours = [1200, 850, 2100, 630, 1750];
let total = 0;

for (let listeningHours of userListeningHours) {
  total += listeningHours;
}

console.log("Total listening hours: "  + total);                        // 6530
console.log("Average: " + total / userListeningHours.length);       // 1306

Writing i < 5 instead of i < array.length is one of the most common mistake. The moment the array grows or shrinks, the hardcoded number becomes wrong and elements get skipped or the loop crashes. Hence, its a good practice to use .length.

💡
If you need the position number, use for. If you need the value, use for...of.

const with Arrays

You might think declaring an Array with const would prevent the user from adding or extracting the elements from that array, it would become static. The modification on it would fail. Interestingly:

const playlist = ["Blinding Lights", "As It Was", "Starboy"];

// Works, you CAN change elements inside a const array
playlist[0] = "Flowers";
console.log(playlist);
// ["Flowers", "As It Was", "Starboy"]

// Fails, you CANNOT reassign the whole variable
playlist = ["New playlist"];
// TypeError: Assignment to constant variable.

What Happens? const locks the reference. The variable must always point to the same array in memory. But it doesn't lock what's inside that array. Hence, it can be freely read, updated, and even add or remove elements. Make use of const for arrays.

Nested Arrays

Arrays can contain another array inside it. This is called a nested array or 2D array. It is used to make grid-shaped data for a game board, a weekly schedule, a table of stats, or a pixel grid.

// Each row = one day's top 3 tracks on the chart
const weeklyChart = [
  ["Flowers", "Blinding Lights", "As It Was"],   // Monday
  ["Levitating", "Stay", "Heat Waves"],       // Tuesday
  ["Cruel Summer", "Flowers", "Calm Down"]     // Wednesday
];

// Access — use weeklyChart[row][column]
console.log(weeklyChart[0]);         // ["Flowers", "Blinding Lights", "As It Was"]
console.log(weeklyChart[0][0]);      // "Flowers"     — Monday #1
console.log(weeklyChart[1][2]);      // "Heat Waves"  — Tuesday #3
console.log(weeklyChart[2][1]);      // "Flowers"     — Wednesday #2

// Loop over each day's #1 track
for (let i = 0; i < weeklyChart.length; i++) {
  console.log("Day " + (i+1) + " #1: " + weeklyChart[i][0]);
}
// Day 1 #1: Flowers
// Day 2 #1: Levitating
// Day 3 #1: Cruel Summer

Checking If Something Is an Array

We know that we can check the data type of a variable with typeof, but this is not true in the case of an Array.

const playlist = ["Blinding Lights", "As It Was"];

// typeof gives wrong answer for arrays
console.log(typeof playlist);           // object
// doesn't return array

// Use Array.isArray() to know the type
console.log(Array.isArray(playlist));    // true
console.log(Array.isArray("hello"));     // false
console.log(Array.isArray(42));          // false
console.log(Array.isArray([]));          // true
// true for an empty array

// Use case
// Check before loop
function printTracks(data) {
  if (!Array.isArray(data)) {
    console.log("Expected an array of tracks");
    return;
  }
  for (let track of data) {
    console.log(track);
  }
}

printTracks(playlist);   
// Blinding Lights  
// As It Was

printTracks("Flowers");   // "Expected an array of tracks!"

In JavaScript, arrays are technically a special kind of object. So typeof [] returns "object", not "array". Hence, Array.isArray() is used to detect arrays and not typeof.

Quick Shuffle

Operation Syntax Notes
Create const a = [v1, v2] Always use literal syntax
Read element a[0] Index starts at 0
Last element a[a.length - 1] Never hardcode the last index
Update a[2] = newValue Mutates in place
Count a.length Property, not a method, no ()
Loop (index) for (let i = 0; i < a.length; i++) When you need index
Loop (value) for (let item of a) Preferred when value i needed and not index
const rule a[0] = x (correct) ; a = [] (error) Contents mutable, variable not
Nested access a[row][col] 2D array element
Type check Array.isArray(a) Not typeof, that gives "object"

References:

Simply JavaScript

Part 20 of 25

JavaScript is a quirky language. To master it, one should know to avoid its hidden traps along with its logic. This series showcase my journey through JS: the pain points, the breakthroughs, and the coding standards that I adopted from my mentors.

Up next

JavaScript Control Flow: If-Else, Switch, and Ternary Operators Explained

From Static Lines to Dynamic Worlds: Building Logic with Conditional Statements