⇧
vadnica-logo
Editor My Blog Password Manager Finance My Services About the Project Telegram O meni O meni

JavaScript Arrays

Arrays are one of the most important data structures in JavaScript. They allow storing multiple values in a single variable, making it easy and efficient to work with large amounts of data. Arrays are dynamic, meaning you can add or remove elements at any time, and JavaScript automatically manages their size. With arrays, you can store different data types - from numbers, strings, objects to other arrays. Each element in an array has a unique index, starting at 0, which allows fast and easy access to individual values.

EXAMPLE
RESULT

Creating an Array

An array is a special variable that can hold more than one value. If we had a list of items (e.g., a list of fruits), storing each fruit in a separate variable would look like this:

let fruit1 = "Strawberries";
let fruit2 = "Peaches";
let fruit3 = "Blueberries";

But what if we want to browse the fruits and find a specific one? And suppose it is not just three fruits, but 300. The solution is an array. An array allows storing a large number of values under one name, which we access via an index number. Below is an example of how to write the above variables as an array:

const fruits = ["Strawberries", "Peaches", "Blueberries"];

The first index is always 0.

It is common practice to declare arrays with the const keyword. Spaces and line breaks do not matter, so we can also write:

const fruits = [
    "Strawberries",
    "Peaches",
    "Blueberries"
];

We can first create an empty array, then add elements to it one by one. Example:

const fruits = [];
fruits[0] = "Strawberries";
fruits[1] = "Peaches";
fruits[2] = "Blueberries";

The next example will be done using the new keyword and assigning a value.

const fruits = new Array("Strawberries", "Peaches", "Blueberries");

All the above methods work the same, but using the new Array constructor is not necessary. For simplicity, readability, and faster execution, we recommend using array literals, as shown in the first example.

mixedArray[0] = Date.now;
mixedArray[1] = Function;
mixedArray[2] = fruits;

JavaScript variables can be objects, while arrays are a special type of object. Therefore, we can store variables of different types in the same array. In an array, we can store objects, functions, or other arrays. The real power of arrays lies in their built-in properties and methods.

fruits.length // returns the number of elements
fruits.sort() // sorting

Creating and Basic Properties of Arrays

Arrays are one of the most important data structures in JavaScript. They allow storing multiple values in a single variable, making it easy and efficient to work with large amounts of data. Arrays are dynamic, meaning you can add or remove elements at any time, and JavaScript automatically manages their size. Each element in an array has a unique index, starting at 0, which allows fast and easy access to individual values.

Methods for Working with Arrays

There are numerous methods available for working with arrays, divided into categories: mutating (modify the original array, e.g., push, pop, splice, sort) and non-mutating (return a new array, e.g., slice, map, filter). Searching for elements is done with indexOf, includes, find, and findIndex.

Complete Overview of Array Methods and Properties (Cheat Sheet)

The table below shows all major methods and properties of Array objects in JavaScript, categorized by type (creation, access, search, modification, transformation, conversion). For each method, the description of operation, syntax, and a concrete code example are provided.

Name Description Syntax Example
new Array() Constructor for creating a new array. new Array(element1, element2, ...) let arr = new Array(1, 2, 3);
[] (Literal) Fastest way to create an array (recommended). [element1, element2, ...] let arr = [1, 2, 3];
constructor Returns the function that created the Array object prototype. array.constructor arr.constructor; // function Array() { ... }
prototype Allows adding properties and methods to the Array object. Array.prototype Array.prototype.newMethod = function() { ... };
isArray() Checks if an object is an array. Array.isArray(object) Array.isArray([1, 2]); // true
length Sets or returns the number of elements in the array. array.length let len = arr.length;
[index] Access element by index (starts at 0). array[index] let first = arr[0];
at() Returns the element at a specific index (supports negative indices). array.at(index) arr.at(-1); // Last element
with() Returns a new array with an updated element at a specific index (immutable). array.with(index, newValue) arr.with(0, "new"); // New array, does not modify original
indexOf() Returns the index of the first occurrence of an element (-1 if not found). array.indexOf(element, startIndex) arr.indexOf(2); // 1
lastIndexOf() Returns the index of the last occurrence of an element. array.lastIndexOf(element) arr.lastIndexOf(2); // 1
includes() Returns true if the array contains the element. array.includes(element) arr.includes(2); // true
find() Returns the first element that satisfies the condition. array.find(condition) arr.find(x => x > 5); // First number greater than 5
findIndex() Returns the index of the first element that satisfies the condition. array.findIndex(condition) arr.findIndex(x => x > 5); // 3
filter() Returns a new array with elements that satisfy the condition. array.filter(condition) arr.filter(x => x > 5); // [6, 7, 8]
push() Adds element(s) to the end of the array. Returns new length. array.push(element1, ...) arr.push(4); // arr = [1, 2, 3, 4]
pop() Removes the last element and returns it. array.pop() let last = arr.pop(); // arr = [1, 2]
unshift() Adds element(s) to the beginning of the array. Returns new length. array.unshift(element1, ...) arr.unshift(0); // arr = [0, 1, 2]
shift() Removes the first element and returns it. array.shift() let first = arr.shift(); // arr = [2, 3]
splice() Adds or removes elements at any position. array.splice(start, deleteCount, element1, ...) arr.splice(1, 1, "new"); // Removes 1 element at index 1 and adds "new"
sort() Sorts elements in the array (default: alphabetically/ASCII). array.sort(function) arr.sort((a, b) => a - b); // Numeric sort
reverse() Reverses the order of elements in the array. array.reverse() arr.reverse(); // [3, 2, 1]
map() Returns a new array with results of calling a function on every element. array.map(function) arr.map(x => x * 2); // [2, 4, 6]
forEach() Executes a function on every element (returns nothing). array.forEach(function) arr.forEach(x => console.log(x));
reduce() Reduces the array to a single value (accumulator). array.reduce(function, initialValue) arr.reduce((acc, x) => acc + x, 0); // Sum
reduceRight() Reduces the array to a single value (from right to left). array.reduceRight(function, initialValue) arr.reduceRight((acc, x) => acc + x, 0);
some() Returns true if at least one element satisfies the condition. array.some(condition) arr.some(x => x > 5); // true
every() Returns true if all elements satisfy the condition. array.every(condition) arr.every(x => x > 0); // true
join() Joins all elements into a string with a specified separator. array.join(separator) arr.join(", "); // "1, 2, 3"
slice() Slices a part of the array and returns a new array (does not modify original). array.slice(start, end) arr.slice(1, 3); // [2, 3]
concat() Merges two or more arrays into a new array. array.concat(array2, ...) arr.concat([4, 5]); // [1, 2, 3, 4, 5]
toString() Converts the array to a string (same as join(",")). array.toString() arr.toString(); // "1,2,3"
valueOf() Returns the primitive value of the array (the array itself). array.valueOf() arr.valueOf(); // [1, 2, 3]
entries() Returns an iterator object with pairs [index, value]. array.entries() ...arr.entries(); // [[0, 1], [1, 2], ...]
keys() Returns an iterator object with keys (indices) of the array. array.keys() ...arr.keys(); // [0, 1, 2]
values() Returns an iterator object with values of the array. array.values() ...arr.values(); // [1, 2, 3]