If you’re new to JavaScript, you’ll get to a point where you’ll have to understand the concepts behind arrays, it’s implementations and how it works; which is why I’ve taken my time to break everything down in this article to explain in-depth everything you need know and understand about arrays in JavaScript programming language.
Arrays just like any other programming language, enables storing a collection of multiple items under a single variable name and has members for performing common array operations.
Some Characteristics of JavaScript Arrays
- They are resizable and can contain a mix of different data types
- They are not associative arrays and so, array elements cannot be accessed using arbitrary strings as indexes, but must be accessed using non-negative integers (or their respective string form) as indexes.
- They are zero-indexed which means that the first element of an array is at index 0 while the last element is at the value of the array’s length property minus 1.
- JavaScript array-copy operations create shallow copies.
Note: All standard built-in copy operations with any JavaScript objects create shallow copies, rather than deep copies.
ARRAY INDICES
JavaScript syntax requires properties beginning with a digit to be accessed using bracket [] notation instead of dot notation. You can as well quote the array indices for instance years[‘5’] instead of years[5], though they are usually not necessary.
But years[5] and years[05] would refer to two different slots on the years object.
console.log(years["5"] != years["05"]); // indices 2 is not equal to 02
Only years[“5”] is an actual array index. years[“05”] is an arbitrary string property that will not be visited in array iteration.
Relationship between length and numerical properties
JavaScript array’s length property and numerical properties are connected.
const years = [];
years.push("Januaray", "February", "March");
console.log(years.length); // 3
Array Methods and Empty slots
Methods that do an in check before accessing the index and do not conflate empty slots with undefined:
concat(); copyWithin(); every(); filter(); flat(); flatMap(); forEach(); indexOf(); lastIndexOf(); map(); reduce(); reduceRight(); reverse(); slice(); some(); sort(); splice();
Methods that treat empty slots as if they are undefined:
entries(); fill(); find(); findIndex(); findLast(); findLastIndex(); group(); groupToMap(); includes(); join(); keys(); toLocalString(); values();
Copying methods and mutating methods:
concat(), filter(), flat(), flatMap(), map(), slice(), splice()
Creating new arrays with the Array base constructor:
toReversed(), toSorted(), toSpliced(), with()
CONSTRUCTOR
- Array() — Creates a new Array object.
STATIC PROPERTIES
- Array[@@special] — Returns the Array constructor
STATIC METHODS
- Array.from() — Creates a new Array instance from an iterable or array-like object
- Array.fromAsync() — Returns a new Array instance from an async iterable, iterable, or array-like object.
- Array.isArray() — Returns true if the argument is an array, or false otherwise.
- Array.of() — Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
INSTANCE PROPERTIES
These properties are defined on Array.prototype and shared by all Array instances.
- Array.prototype.constructor — The constructor function that created the instance object. For Array instances, the initial value is the Array constructor.
- Array.prototype[@@unscopables] — Contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for with statement-binding purposes.
- Length — Reflects the number of elements in an array.
INSTANCE METHODS
- Array.prototype.at() — Returns the array item at the given index. Accepts negative integers, which count back from the last item.
- Array.prototype.concat() — Returns a new array that is the calling array joined with other array(s) and/or value(s).
- Array.prototype.copyWithin() — Copies a sequence of array elements within an array.
- Array.prototype.entries() — Returns a new array iterator object that contains the key/value pairs for each index in an array.
- Array.prototype.every() — Returns true if every element in the calling array satisfies the testing function.
- Array.prototype.fill() — Fills all the elements of an array from a start index to an end index with a static value.
- Array.prototype.filter() — Returns a new array containing all elements of the calling array for which the provided filtering function returns true.
- Array.prototype.find() — Returns the value of the first element in the array that satisfies the provided testing function, or undefined if not appropriate element is found.
- Array.prototype.findIndex() — Returns the index of the first element in the array that satisfies the provided testing function, or -1 if no appropriate element was found.
- Array.prototype.findLast() — Returns the value of the last element in the array that satisfies the provided testing function, or undefined if no appropriate element is found.
- Array.prototype.findLastIndex() — Returns the index of the last element in the array that satisfies the provided testing function, or -1 if no appropriate element was found.
- Array.prototype.flat() — Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.
- Array.prototype.flatMap() — Returns a new array formed by applying a given callback function to each element of the calling array, and then flattening the result by one level.
- Array.prototype.forEach() — Calls a function for each element in the calling array.
- Array.prototype.group() — Groups the elements of an array into an object according to the strings returned by a test function.
- Array.prototype.groupToMap() — Groups the elements of an array into a Map according to values returned by a test function.
- Array.prototype.includes() — Determines whether the calling array contains a value, returning true or false as appropriate.
- Array.prototype.indexOf() — Returns the first (least) index at which a given element can be found in the calling array.
- Array.prototype.join() — Joins all elements of an array into a string.
- Array.prototype.keys() — Returns a new array iterator that contains the keys for each index in the calling array.
- Array.prototype.lastIndexOf() — Returns the last (greatest) index at which a given element can be found in the calling array, or -1 if none is found.
- Array.prototype.map() — Returns a new array containing the results of invoking a function on every element in the calling array.
- Array.prototype.pop() — Removes the last element from an array and returns that element.
- Array.prototype.push() — Adds one or more elements to the end of an array, and returns the new length of the array.
- Array.prototype.reduce() — Executes a user-supplied “reducer” callback function on each element of the array (from left to right), to reduce it to a single value.
- Array.prototype.reduceRight() — Executes a user-supplied “reducer” callback function on each element of the array (from right to left), to reduce it to a single value.
- Array.prototype.reverse() — Reverses the order of the elements of an array in place. (First becomes the last, last becomes first).
- Array.prototype.shift() — Removes the first element from an array and returns that element.
- Array.prototype.slice() — Extracts a section of the calling array and returns a new array.
- Array.prototype.some() — Returns true if at least one element in the calling array satisfies the provided testing function.
- Array.prototype.sort() — Sorts the elements of an array in place and returns the array.
- Array.prototype.splice() — Adds and/or removes elements from an array.
- Array.prototype.toLocaleString() — Returns a localized string representing the calling array and it’s elements. Overrides the Object.prototype.toLocaleString() method.
- Array.prototype.toReversed() — Returns a new array with the elements in reversed order, without modifying the original array.
- Array.prototype.toSorted() — Returns a new array with the elements sorted in ascending order, without modifying the original array.
- Array.prototype.toSpliced() — Returns a new array with some elements removed and/or replaced at a given index, without modifying the original array.
- Array.prototupe.toString() — Returns a string representing the calling array and its elements. Overrides the Object.prototype.toString() methods.
- Array.prototype.unshift() — Adds one or more elements to the front of an array, and returns the new length of the array.
- Array.prototype.values() — Returns a new array iterator object that contains the values for each index in the array.
- Array.prototype.with() — Returns a new array with the element at the given index replaced with the given value, without modifying the original array.
- Array.prototype[@@iterator]() — An alias for the values() method by default
WORKING WITH JAVASCRIPT ARRAY METHODS
Creating an array
// Created using array literal notation
const keyboard1 = ["A", "B", "C", "D", "E", "F", "G"];
console.log(`The total number of keys on keyboard1 is ${keyboard1.length}`);
// Created using the Array() constructor
const keyboard2 = new Array("A", "B", "C", "D", "E", "F", "G");
console.log(`The total number of keys on keyboard2 is ${keyboard2.length}`);
// Created using String.prototype.split()
const keyboard3 = "A, B, C, D, E, F, G".split(", ");
console.log(`The total number of keys on keyboard3 is ${keyboard3.length}`);
Creating a string from an array
const keyboard = ["A", "B", "C", "D", "E", "F", "G"];
const keyboardString = keyboard.join(", ");
console.log(keyboardString);
Accessing an array item by its index
const keyboard = ["A", "B", "C", "D", "E", "F"];
console.log(keyboard[0]); // first element is always 0
console.log(keyboard[1]); // second element is always 1
console.log(keyboard[keyboard.length - 1]); // last element is always one less than the length of the array.
console.log(keyboard[99]); // index number larger than the array's length always returns 'undefined'
Finding the index of an item in an array
const keyboard = ["A", "B", "C", "D", "E", "F"];
console.log(keyboard.indexOf("C"));
Checking if an array contains a certain item
const keyboard = ["A", "B", "C", "D", "E", "F"];
console.log(keyboard.includes("D"));
console.log(keyboard.includes("I"));
// If index)f doesn't returns -1, the array contains the given item.
console.log(keyboard.indexOf("F") !== -1);
console.log(keyboard.indexOf("I") !== -1);
Appending an item to an array
const keyboard = ["A", "B", "C", "D", "E", "F"];
const newKeyboard = keyboard.push("I");
console.log(keyboard);
console.log(newKeyboard);
Removing the last item from an array
const keyboard = ["A", "B", "C", "D", "E", "F"];
const newKeyboard = keyboard.pop();
console.log(keyboard);
console.log(newKeyboard);
Removing multiple items from the end of an array
const keyboard = ["A", "B", "C", "D", "E", "F"];
const start = -3;
const removedKeyboard = keyboard.splice(start);
console.log(keyboard);
console.log(removedKeyboard);
Truncating an array down to just its first N items
const keyboard = ["A", "B", "C", "D", "E", "F"];
const start = 2;
const removedKeyboard = keyboard.splice(start);
console.log(keyboard);
console.log(removedKeyboard);
Removing the first item from an array
const keyboard = ["A", "B", "C", "D", "E", "F"];
const removedKeyboard = keyboard.shift();
console.log(keyboard);
console.log(removedKeyboard);
Removing multiple items from the beginning of an array
const keyboard = ["A", "B", "C", "D", "E", "F"];
const start = 0;
const deleteCount = 3;
const removedKeyboard = keyboard.splice(start, deleteCount);
console.log(keyboard);
console.log(removedKeyboard);
Adding a new first item to an array
const keyboard = ["A", "B", "C", "D", "E", "F", "G"];
const newLength = keyboard.unshift("a");
console.log(keyboard);
console.log(newLength)
Removing a single item by index
const keyboard = ["A", "B", "C", "D", "E", "F", "G"];
const start = keyboard.indexOf("E");
const deleteCount = 1;
const removedKeyboard = keyboard.splice(start, deleteCount);
console.log(keyboard);
console.log(removedKeyboard);
Removing multiple items by index
const keyboard = ["A", "B", "C", "D", "E", "F", "G"];
const start = keyboard.indexOf("E");
const deleteCount = 2;
const removedKeyboard = keyboard.splice(start, deleteCount);
console.log(keyboard);
console.log(removedKeyboard);
Replacing multiple items in an array
const keyboard = ["A", "B", "C", "D", "E", "F", "G"];
const start = -2;
const deleteCount = 2;
const removedKeyboard = keyboard.splice(start, deleteCount, "H", "I")
console.log(keyboard);
console.log(removedKeyboard);
Iterating over an array
const keyboard = ["A", "B", "C", "D", "E", "F", "G"];
for (const keys of keyboard) {
console.log(keys);
}
Calling a function on each element in an array
const keyboard = ["A", "B", "C", "D", "E", "F", "G"];
keyboard.forEach((item, index, array) => {
console.log(item, index);
})
Merging multiple arrays together
const keyboard = ["A", "B", "C", "D", "E", "F", "G"];
const moreKeyboard = ["H", "I", "J"];
const combinedKeyboard = keyboard.concat(moreKeyboard);
console.log(combinedKeyboard);
console.log(keyboard);
console.log(moreKeyboard);
Copying an array
// CREATING SHALLOW COPY
const keyboard = ["A", "B", "C", "D", "E", "F", "G"];
// Copying using spread syntax
const copyKeybaord1 = [...keyboard];
console.log(copyKeybaord1);
// Copying using from() method
const copyKeybaord2 = Array.from(keyboard);
console.log(copyKeybaord2);
// Copying using slice() method
const copyKeybaord3 = keyboard.slice();
console.log(copyKeybaord3);
// CREATING DEEP COPY
const keyboard = ["A", "B", "C", "D", "E", "F", "G"];
// Copying using stringify
const copyKeybaord4 = JSON.parse(JSON.stringify(keyboard));
copyKeybaord4.pop();
console.log(copyKeybaord4);
Note: All built-in array-copy operations(spread, .from(), .slice() and .concat() create shallow copies). What this means is that if you’re assigning an existing array to a new variable, the new variable doesn’t create a copy of either the array or its elements. Instead, the new variable is just a reference or alias, to the original array; that is, the original array’s name and the new variable name are just two names for the exact same object which will always evaluate as strictly equivalent. This means that anytime you make any changes to either the value of the original array or the value of the new variable, the other will change too and vice-versa.
In case you’re interested in learning the difference between shallow and deep copies in JavaScript, you can read more about it here.
const keyboard = ["A", "B", "C", "D", "E", "F", "G"];
const keyboardAlias = keyboard;
console.log(keyboard === keyboardAlias);
keyboard.unshift("a", "b");
console.log(keyboard);
console.log(keyboardAlias);
Using array to tabulate a set of values
const values = [];
for (let x = 0; x < 10; x++) {
values.push([2 ** x, 2 * x ** 2]);
}
console.table(values);
I hope by now you’ve understand the concepts behind arrays in JavaScript. This resources was made possible by the mozilla documentation which I’ve personally been using so far. If you’re looking to learn about JavaScript as a beginner, I highly recommend you check it out.
I hope this article has been so helpful to you. Don’t forget to give me a clap 👏 share this article & follow me on my social media handles: twitter , facebook and youtube.