Skip to main content

JavaScript Arrays

Summary

Introdution to arrays in JavaScript, covering their basic syntax, accessing elements, modifying elements, getting the length, and various array methods. Each method serves different purposes for manipulating arrays.

Introduction to Arrays #

Arrays in JavaScript are a fundamental data structure used to store multiple values in a single variable. They are a type of object that holds a collection of elements, which can be of any data type, including numbers, strings, objects, or even other arrays. Arrays in JavaScript are dynamic, meaning they can grow or shrink in size as needed.

In JavaScript, arrays are zero-indexed, meaning the first element is accessed with an index of 0, the second element with an index of 1, and so on.

Creating an array #

An array named fruits is created and initialized with three string elements: 'apple', 'banana', and 'orange':

// Creating an array
let fruits = ['apple', 'banana', 'orange'];

Examples #

Accessing elements of an array #

Accessing individual elements within the fruits array using their respective indices (0, 1, and 2), and then logging each element to the console with console.log(), resulting in the respective outputs 'apple', 'banana', and 'orange':

// Accessing elements of an array
console.log(fruits[0]); // Output: 'apple'
console.log(fruits[1]); // Output: 'banana'
console.log(fruits[2]); // Output: 'orange'

Modifying elements of an array #

The element at index 1 of the fruits array is modified to contain the value ‘grape’, replacing the previous value ‘banana’. After the modification, the updated fruits array is logged to the console, showing the modified array ['apple', 'grape', 'orange']:

// Modifying elements of an array
fruits[1] = 'grape';
console.log(fruits); // Output: ['apple', 'grape', 'orange']

Getting the length of an array #

The .length property of the fruits array is accessed, which returns the number of elements in the fruits array (3) - apple, grape, orange. The result is then logged to the console:

// Getting the length of an array
console.log(fruits.length); 
// Output: 3

Arrays also come with various built-in methods for performing common operations, such as adding or removing elements, sorting, searching, and iterating over the elements. Some commonly used array methods include push(), pop(), shift(), unshift(), slice(), splice(), forEach(), map(), filter(), reduce(), and sort().


Adding elements to the end of an array #

The .push() method is used to add the string 'kiwi' to the end of the fruits array. The updated array ['apple', 'grape', 'orange', 'kiwi'] is then logged to the console:

// Adding elements to the end of an array
fruits.push('kiwi');
console.log(fruits); // Output: ['apple', 'grape', 'orange', 'kiwi']

Removing the last element of an array #

The .pop() method is used to remove and return the last element of the fruits array, which is 'kiwi'. The removed element is stored in the variable lastFruit, and the updated array ['apple', 'grape', 'orange'] is then logged to the console.

// Removing the last element of an array
let lastFruit = fruits.pop();
console.log(lastFruit); // Output: 'kiwi'
console.log(fruits); // Output: ['apple', 'grape', 'orange']

Removes the first element from an array and return it #

The .shift() method removes the first element from an array and returns that removed element:

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

Adds one or more elements to the beginning of an array and return the length of the array #

The .unshift() method adds one or more elements to the beginning of an array and returns the new length of the array:

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

Return a shallow copy of a portion of an array into a new array #

The .slice() method returns a shallow copy (specific values that are still connected to the original Variable) of a portion of an array into a new array:

let fruits = ['apple', 'banana', 'orange', 'kiwi'];
let slicedFruits = fruits.slice(1, 3);
console.log(slicedFruits); // Output: ['banana', 'orange']

Change the contents of an array by removing/replacing elements and/or adding elements #

The .splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place:

let fruits = ['apple', 'banana', 'orange', 'kiwi'];
fruits.splice(2, 1, 'grape', 'pineapple');
console.log(fruits); // Output: ['apple', 'banana', 'grape', 'pineapple', 'kiwi']

Execute a provided function once for each array element #

The .forEach() method executes a provided function once for each array element:

let numbers = [1, 2, 3, 4, 5];
numbers.forEach(number => console.log(number * 2)); // Output: 2, 4, 6, 8, 10

Create a new array populated with the results of calling a provided function on every element in the calling array #

The .map() method creates a new array populated with the results of calling a provided function on every element in the calling array:

let numbers = [1, 2, 3, 4, 5];
let doubledNumbers = numbers.map(number => number * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]

Creates an array with all elements that pass the filter by the provided function #

The .filter() method creates a new array with all elements that pass the test implemented by the provided function.

let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter(number => number % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]

Execute a reducer function on each element of the array #

The .reduce() method executes a reducer function on each element of the array, resulting in a single output value:

let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // Output: 15

Sort the elements of an array #

The .sort() method sorts the elements of an array in place and returns the sorted array:

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

Further readings #

Sources and recommended, further resources on the topic:

Author

Jonas Jared Jacek • J15k

Jonas Jared Jacek (J15k)

Jonas works as project manager, web designer, and web developer since 2001. On top of that, he is a Linux system administrator with a broad interest in things related to programming, architecture, and design. See: https://www.j15k.com/

License

License: JavaScript Arrays by Jonas Jared Jacek is licensed under CC BY-NC-SA 4.0.

This license requires that reusers give credit to the creator. It allows reusers to distribute, remix, adapt, and build upon the material in any medium or format, for noncommercial purposes only. If others modify or adapt the material, they must license the modified material under identical terms. To give credit, provide a link back to the original source, the author, and the license e.g. like this:

<p xmlns:cc="http://creativecommons.org/ns#" xmlns:dct="http://purl.org/dc/terms/"><a property="dct:title" rel="cc:attributionURL" href="https://www.ditig.com/publications/javascript-arrays">JavaScript Arrays</a> by <a rel="cc:attributionURL dct:creator" property="cc:attributionName" href="https://www.j15k.com/">Jonas Jared Jacek</a> is licensed under <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank" rel="license noopener noreferrer">CC BY-NC-SA 4.0</a>.</p>

For more information see the DITig legal page.


“Good design comes from a deep understanding of the technologies behind the scenes.”

Jeffrey Veen, American designer and design strategistThe Art & Science of Web Design, - IT quotes