Arrays in JavaScript

Arrays are a fundamental data structure in JavaScript that allows you to store multiple values in a single variable.

An array can hold a collection of values, which can be of different types, such as numbers, strings, or even other arrays. This section will introduce arrays, their use, and common ways to manipulate array elements.

What is an Array?

An array is a list-like object that stores multiple values, called elements, in a single variable.

Arrays can be created using square brackets [], with elements separated by commas.

Here's how:

let fruits = ['apple', 'banana', 'cherry'];
let numbers = [1, 2, 3, 4, 5];
let mixed = [1, 'hello', true];

Accessing Array Elements

You can access elements in an array using their "index". Each element in the array has a position called an index. The first element has an index of 0, the second element has an index of 1, and so on.

Once you have an array, we can access it then using square brackets like in this example:

let fruits = ['apple', 'banana', 'cherry'];

console.log(fruits[0]); // Outputs: apple
console.log(fruits[1]); // Outputs: banana
console.log(fruits[2]); // Outputs: cherry

Modifying Array Elements

You can change the value of an array element by accessing its index and assigning a new value.

Example:

let fruits = ['apple', 'banana', 'cherry'];

fruits[1] = 'blueberry';
console.log(fruits); // Outputs: ['apple', 'blueberry', 'cherry']

Adding and Removing Elements

Arrays have several methods to add or remove elements:

  1. push(): Adds one or more elements to the end of the array.
let fruits = ['apple', 'banana'];
fruits.push('cherry');
console.log(fruits); // Outputs: ['apple', 'banana', 'cherry']
  1. pop(): Removes the last element from the array.
let fruits = ['apple', 'banana', 'cherry'];
fruits.pop();
console.log(fruits); // Outputs: ['apple', 'banana']
  1. unshift(): Adds one or more elements to the beginning of the array.
let fruits = ['banana', 'cherry'];
fruits.unshift('apple');
console.log(fruits); // Outputs: ['apple', 'banana', 'cherry']
  1. shift(): Removes the first element from the array.
let fruits = ['apple', 'banana', 'cherry'];
fruits.shift();
console.log(fruits); // Outputs: ['banana', 'cherry']

Array Length

Often you'll want to count how many items are in your array. You can use an array's length property to return the number of elements in the array.

let fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.length); // Outputs: 3

Useful Array Methods

Arrays come with many built-in methods that make it easier to work with them. Here are a few practical methods you can use with examples:

  1. indexOf(): Finds the index of the first occurrence of a specified value.
let fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.indexOf('banana')); // Outputs: 1
  1. includes(): Checks if an array contains a specified value.
let fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.includes('banana')); // Outputs: true
console.log(fruits.includes('grape')); // Outputs: false
  1. slice(): Returns a new array containing a portion of an existing array.
let fruits = ['apple', 'banana', 'cherry'];
let citrus = fruits.slice(0, 2);
console.log(citrus); // Outputs: ['apple', 'banana']
  1. join(): Joins all elements of an array into a string.
let fruits = ['apple', 'banana', 'cherry'];
let fruitString = fruits.join(', ');
console.log(fruitString); // Outputs: 'apple, banana, cherry'

Mutability and Immutability Using Arrays

Mutability and immutability are concepts in programming that describe whether an object can be changed after it's created.

Mutability:

  • Mutable objects can be modified after creation
  • You can change their values or properties

Immutability:

  • Immutable objects cannot be changed after creation
  • Any operation that seems to modify them creates a new object

Key differences:

  1. Changeability: Mutable objects can change, immutable objects cannot
  2. Memory use: Mutable objects may use less memory as they can be modified in place
  3. Thread safety: Immutable objects are often safer in multi-threaded environments
  4. Predictability: Immutable objects can be easier to reason about as their state doesn't change

Arrays in JavaScript are mutable, meaning you can change their elements after creating them. Methods like push(), pop(), shift(), unshift(), and direct assignment (e.g., fruits[1] = 'blueberry') modify the original array.

let fruits = ['apple', 'banana', 'cherry'];
fruits.push('date'); // Adds 'date' to the end
console.log(fruits); // Outputs: ['apple', 'banana', 'cherry', 'date']

Some array methods behave immutably, such as slice(), concat(), and map(), which return new arrays while leaving the original array unchanged.

let fruits = ['apple', 'banana', 'cherry'];
let moreFruits = fruits.concat(['date', 'elderberry']);
console.log(fruits); // Outputs: ['apple', 'banana', 'cherry']
console.log(moreFruits); // Outputs: ['apple', 'banana', 'cherry', 'date', 'elderberry']

Skills to Practice

  1. Creating Arrays: Use square brackets [] to create arrays with elements separated by commas.

    • Examples: ['apple', 'banana', 'cherry'], [1, 2, 3, 4, 5], [1, 'hello', true]
  2. Accessing Elements: Use the element's index to access its value. Remember, the first element is at index 0.

    • Example: console.log(fruits[0]);
  3. Modifying Elements: Change the value of an element by accessing its index and assigning a new value.

    • Example: fruits[1] = 'blueberry';
  4. Adding and Removing Elements: Use methods like push(), pop(), unshift(), and shift() to add or remove elements.

    • Examples: fruits.push('cherry');, fruits.pop();
  5. Array Length: Use the length property to get the number of elements in an array.

    • Example: console.log(fruits.length);
  6. Useful Methods: Use methods like indexOf(), includes(), slice(), and join() to work with arrays.

    • Examples: fruits.indexOf('banana');, fruits.includes('grape');, fruits.slice(0, 2);, fruits.join(', ');
  7. Mutability and Immutability: Understand that arrays can be changed (mutable) or create new arrays without changing the original (immutable).

    • Examples: fruits.push('date');, let moreFruits = fruits.concat(['date', 'elderberry']);

Arrays are one of the core concepts in JavaScript that are worth learning deeply. Arrays provide a flexible way to store and manage multiple values, making your code more dynamic and powerful.

Next, we will explore strings in more depth as we only touched off them briefly, but you'll use them heavily in your JS journey.

BeginnerJavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.