Back to JavaScript
2026-02-076 min read

JavaScript Arrays

Learn JavaScript Arrays step by step with clear examples and exercises.

Why This Matters

Welcome to our full guide on JavaScript Arrays! In this tutorial, we will delve deep into the world of arrays, exploring their practical applications, common mistakes, and advanced techniques. By the end of this lesson, you will be well-equipped to tackle complex problems, write robust code, and excel in interviews.

Why This Matters

JavaScript arrays are a fundamental data structure used for storing multiple values under a single variable name. They play a crucial role in JavaScript programming, as they allow us to manipulate collections of data efficiently. Understanding arrays is essential for solving complex problems, writing robust code, and acing interviews.

Prerequisites

Before we dive into the core concept, it's important that you have a good understanding of the following topics:

  • Basic JavaScript syntax (variables, operators, expressions)
  • Control structures (if statements, loops)
  • Functions (defining and calling functions)

If you're not familiar with these concepts, consider brushing up on them before proceeding.

Core Concept

Creating Arrays

To create an array in JavaScript, we use square brackets [] to enclose a list of values separated by commas. For example:

let fruits = ["apple", "banana", "orange"];
console.log(fruits); // Output: [ 'apple', 'banana', 'orange' ]

In this example, we create an array called fruits and assign it three elements: "apple," "banana," and "orange." The elements are numbered starting from 0 (zero).

Accessing Array Elements

To access an element in an array, we use the index of the element within square brackets. Remember that indices start at 0. For example:

console.log(fruits[0]); // Output: 'apple'

In this case, we access the first element (index 0) of the fruits array and log its value to the console.

Modifying Array Elements

We can modify an existing array element by assigning a new value to it using the index:

fruits[0] = "kiwi";
console.log(fruits); // Output: [ 'kiwi', 'banana', 'orange' ]

Here, we change the first element of the fruits array from "apple" to "kiwi."

Adding Array Elements

To add an element to the end of an array, we can use the push() method:

fruits.push("grape");
console.log(fruits); // Output: [ 'kiwi', 'banana', 'orange', 'grape' ]

In this example, we add "grape" to the end of the fruits array using the push() method.

Removing Array Elements

We can remove an element from an array using the splice() method, which takes two arguments: the index of the element to be removed and the number of elements to be removed (optional). For example:

fruits.splice(1, 1);
console.log(fruits); // Output: [ 'kiwi', 'orange' ]

Here, we remove the second element ("banana") from the fruits array using the splice() method with an index of 1 and a count of 1.

Checking Array Length

To find out how many elements an array has, we can use the length property:

console.log(fruits.length); // Output: 2

In this example, we check the length of the fruits array and see that it contains two elements.

Iterating Over Arrays

We can iterate over an array using a for loop or the forEach() method. For example:

let fruits = ["apple", "banana", "orange"];

// Using a for loop
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}

// Using the forEach() method
fruits.forEach((fruit) => console.log(fruit));

In this example, we iterate over the fruits array using both a for loop and the forEach() method.

Worked Example

Let's create an array of numbers and perform some operations on it:

let numbers = [1, 2, 3, 4, 5];
console.log(numbers); // Output: [ 1, 2, 3, 4, 5 ]

// Access the first element
console.log(numbers[0]); // Output: 1

// Modify the second element
numbers[1] = 10;
console.log(numbers); // Output: [ 1, 10, 3, 4, 5 ]

// Add an element to the end
numbers.push(6);
console.log(numbers); // Output: [ 1, 10, 3, 4, 5, 6 ]

// Remove the first occurrence of the number 3
numbers.splice(numbers.indexOf(3), 1);
console.log(numbers); // Output: [ 1, 10, 4, 5, 6 ]

// Check the length of the array
console.log(numbers.length); // Output: 5

In this example, we create an array called numbers, perform various operations on it (accessing, modifying, adding, and removing elements), and check its length.

Common Mistakes

  • Forgetting to initialize the array:

Incorrect:

let numbers =;
console.log(numbers); // Output: undefined

Correct:

let numbers = [];
console.log(numbers); // Output: []
  • Accessing an out-of-bounds element:

Incorrect:

console.log(fruits[5]); // Output: undefined

Correct:

if (fruits.length > 4) {
console.log(fruits[4]); // Output: 'banana'
} else {
console.log("Array index out of bounds");
}
  • Forgetting to declare the array variable:

Incorrect:

let numbers = [1, 2, 3];
console.log(numbers[4]); // Output: undefined

Correct:

let numbers;
numbers = [1, 2, 3];
console.log(numbers[4]); // Output: undefined

Additional Mistakes

  • Assuming that array indices start at 1 instead of 0:

Incorrect:

console.log(fruits[1]); // Output: 'banana' (expected 'kiwi')

Correct:

if (fruits.length > 0) {
console.log(fruits[0]); // Output: 'kiwi'
} else {
console.log("Array is empty");
}
  • Misusing the pop() method to remove elements from arbitrary positions:

Incorrect:

fruits.pop(1); // This removes the last element, not the element at index 1
console.log(fruits); // Output: [ 'kiwi' ]

Correct:

let removed = fruits.splice(1, 1); // Removes the element at index 1
console.log(removed); // Output: [ 'banana' ]
console.log(fruits); // Output: [ 'kiwi', 'orange' ]
  • Using length to remove elements from an array:

Incorrect:

fruits.length = 2; // This removes the last two elements, not the specified ones
console.log(fruits); // Output: [ 'kiwi' ]

Correct:

fruits.splice(2); // Removes all elements from index 2 and onwards
console.log(fruits); // Output: [ 'kiwi' ]

Practice Questions

  1. Write a script that creates an array of strings and adds the string "hello" to the end of the array.
  2. Write a script that removes the first occurrence of the string "apple" from an array of fruits if it exists.
  3. Write a script that finds the index of the largest number in an array of numbers.
  4. Write a script that sorts an array of strings alphabetically and logs the sorted array.
  5. Write a script that removes all occurrences of the number 3 from an array of numbers.
  6. Write a script that finds the sum of all even numbers in an array of numbers.
  7. Write a script that counts the number of vowels in an array of strings.
  8. Write a script that checks if an array contains any duplicate elements.
  9. Write a script that merges two arrays into one sorted array.
  10. Write a script that reverses the order of elements in an array.

FAQ

How do I create an empty array?

To create an empty array, simply use square brackets [] without any elements:

let myArray = [];
console.log(myArray); // Output: []

Can I access array elements using negative indices?

Yes, you can access array elements using negative indices in JavaScript. Negative indices count from the end of the array, with -1 referring to the last element, -2 referring to the second-to-last element, and so on:

let fruits = ["apple", "banana", "orange"];
console.log(fruits[-1]); // Output: 'orange'

How do I find the index of a specific element in an array?

To find the index of a specific element in an array, use the indexOf() method:

let fruits = ["apple", "banana", "orange"];
console.log(fruits.indexOf("banana")); // Output: 1

How do I find the last index of a specific element in an array?

To find the last index of a specific element in an array, use the lastIndexOf() method:

let fruits = ["apple", "banana", "orange", "banana"];
console.log(fruits.lastIndexOf("banana")); // Output: 3

How do I check if an array contains a specific element?

To check if an array contains a specific element, use the includes() method or a for loop:

let fruits = ["apple", "banana", "orange"];
console.log(fruits.includes("banana")); // Output: true

// Using a for loop
for (let i = 0; i < fruits.length; i++) {
if (fruits[i] === "banana") {
console.log(true);
break;
}
}

How do I sort an array of objects?

To sort an array of objects, you can use the sort() method and provide a comparison function:

let people = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 20 }
];

people.sort((a, b) => a.age - b.age);
console.log(people); // Output: [ { name: 'Charlie', age: 20 }, { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 } ]
JavaScript Arrays | JavaScript | XQA Learn