Back to JavaScript
2026-02-276 min read

Lists (JavaScript)

Learn Lists (JavaScript) step by step with clear examples and exercises.

Why This Matters

Lists are a fundamental data structure in programming, and JavaScript's implementation of lists through arrays is crucial for handling various tasks efficiently. In this tutorial, we will delve into the practical aspects of working with lists in JavaScript, focusing on real-world scenarios and common mistakes that you might encounter. By the end of this lesson, you'll be well-equipped to tackle list-related problems confidently.

Why This Matters

Lists provide a way to store multiple items efficiently, allowing for easy access, modification, and manipulation. In JavaScript, lists can be represented using arrays, which are dynamic and allow elements of different data types. Understanding how to work with lists is crucial for solving a wide range of problems, from basic calculations to complex algorithms. This knowledge will also help you prepare for interviews and real-world programming tasks.

Prerequisites

Before diving into JavaScript lists, it's essential to have a good understanding of the following concepts:

  1. Basic JavaScript syntax (variables, operators, control structures)
  2. Functions and function declarations
  3. Objects and properties
  4. Looping constructs (for loops, for-of loops, and while loops)
  5. Understanding of data types in JavaScript
  6. Familiarity with basic mathematical operations

Core Concept

Creating Lists

In JavaScript, lists are represented using arrays. To create an array, you can use the Array constructor or simply enclose comma-separated values within square brackets. Here's an example of creating a simple list:

// Using the Array constructor
let list1 = new Array(5); // Creates an array with 5 empty slots
console.log(list1); // Output: [empty × 5]

// Creating an array using square brackets
let list2 = ['apple', 'banana', 'cherry'];
console.log(list2); // Output: ['apple', 'banana', 'cherry']

Accessing and Modifying Elements

To access elements in a JavaScript array, you can use their index (starting at 0). To modify an element, simply assign a new value to its index. Here's an example:

let list3 = ['apple', 'banana', 'cherry'];
console.log(list3[1]); // Output: banana
list3[2] = 'orange';
console.log(list3); // Output: ['apple', 'banana', 'orange']

Adding and Removing Elements

To add an element to the end of a JavaScript array, you can use the push() method. To remove the last element, you can use the pop() method. Here's an example:

let list4 = ['apple', 'banana'];
list4.push('orange'); // Adds orange to the end of the array
console.log(list4); // Output: ['apple', 'banana', 'orange']
list4.pop(); // Removes the last element (orange)
console.log(list4); // Output: ['apple', 'banana']

Iterating through Arrays

To iterate through an array in JavaScript, you can use a for loop or a for-of loop. Here's an example using both methods:

let list5 = ['apple', 'banana', 'cherry'];
for (let i = 0; i < list5.length; i++) {
console.log(list5[i]); // Output: apple, banana, cherry
}

for (let fruit of list5) {
console.log(fruit); // Output: apple, banana, cherry
}

Manipulating Arrays

JavaScript provides several methods for manipulating arrays, such as shift(), unshift(), splice(), and more. These methods allow you to add, remove, or modify elements at specific positions within the array.

Shift and Unshift

  • The shift() method removes the first element from an array and returns it.
  • The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

Here's an example using both methods:

let list6 = ['apple', 'banana', 'cherry'];
console.log(list6.shift()); // Output: apple (the first element is removed)
console.log(list6); // Output: ['banana', 'cherry']

list6.unshift('orange'); // Adds orange to the beginning of the array
console.log(list6); // Output: ['orange', 'banana', 'cherry']

Splice

The splice() method allows you to add, remove, or replace elements at a specific position in an array. It takes up to four arguments: the index at which to start changing the array, the number of elements to be removed (optional), the elements to be added (optional), and the optional starting position for the new elements within the added subset (default is 0).

Here's an example using splice():

let list7 = ['apple', 'banana', 'cherry'];
list7.splice(1, 1, 'grape', 'mango'); // Removes one element at index 1 and adds 'grape' and 'mango' at that position
console.log(list7); // Output: ['apple', 'grape', 'mango', 'cherry']

Worked Example

Let's consider a practical example where we need to find the second-highest number in an array of numbers.

let numbers = [23, 14, 56, 78, 90, 12];
let secondHighest = -1;
let highest = numbers[0];

for (let i = 0; i < numbers.length; i++) {
if (numbers[i] > highest) {
secondHighest = highest;
highest = numbers[i];
} else if (numbers[i] > secondHighest && numbers[i] != highest) {
secondHighest = numbers[i];
}
}

console.log(secondHighest); // Output: 56 (the second-highest number in the array)

Common Mistakes

  1. Forgetting to initialize arrays: Always ensure that you initialize your arrays before using them, as shown in the examples above.
  2. Accessing out-of-bounds elements: Be careful not to access elements beyond the array's length. This will result in undefined or unexpected behavior.
  3. Modifying arrays during iteration: When iterating through an array, avoid modifying it as this can lead to incorrect results and confusing bugs. If you need to modify an array while iterating, consider using a for loop with an index variable instead of a for-of loop.
  4. Confusing arrays with strings: In JavaScript, arrays and strings are both objects, but they behave differently. Be sure to use the appropriate method or operator when working with each data type.
  5. Not handling edge cases: Always consider what happens if an array is empty or contains only one element. For example, when finding the second-highest number in an array, you should handle the case where there are fewer than two numbers in the array.
  6. Using the wrong method for a specific task: JavaScript provides several methods for manipulating arrays, and it's essential to choose the right one for your needs. For example, using shift() when you need to remove the last element can lead to unexpected results.

Practice Questions

  1. Write a function that takes an array of numbers as input and returns the sum of its elements.
  2. Create an array containing the first 10 Fibonacci numbers (0, 1, 1, 2, 3, 5, 8, 13, 21, 34).
  3. Write a function that finds the index of the first occurrence of a specific value in an array. If the value is not found, return -1.
  4. Write a function that sorts an array of numbers in ascending order using the bubble sort algorithm.
  5. Write a function that reverses the elements of an array without using the built-in reverse() method.
  6. Write a function that finds the maximum and minimum values in an array of numbers.
  7. Write a function that checks if an array contains duplicates. If it does, return the duplicate value(s); otherwise, return null.
  8. Write a function that removes all occurrences of a specific value from an array.
  9. Write a function that concatenates two arrays and returns the resulting array.
  10. Write a function that checks if an array is sorted in ascending order. If it is, return true; otherwise, return false.

FAQ

How can I sort an array in JavaScript?

In JavaScript, you can use the sort() method to sort an array. By default, sort() compares elements as strings and sorts them lexicographically. To sort numbers correctly, you can provide a comparison function as an argument to sort(). Here's an example:

let numbers = [34, 15, 88, 2];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers); // Output: [2, 15, 34, 88] (the array sorted in ascending order)

How can I reverse the elements of an array in JavaScript?

To reverse the elements of an array in JavaScript, you can use the reverse() method. Here's an example:

let numbers = [34, 15, 88, 2];
numbers.reverse();
console.log(numbers); // Output: [2, 88, 15, 34] (the array reversed)

How can I find the index of a specific value in an array?

To find the index of a specific value in an array, you can use the indexOf() method. Here's an example:

let numbers = [34, 15, 88, 2];
console.log(numbers.indexOf(15)); // Output: 1 (the index of the first occurrence of 15)
Lists (JavaScript) | JavaScript | XQA Learn