An array is a variable that contains a list of data, where each element has its own index and can be accessed using that index. Array indexing starts from zero. An array can contain different types of data: other arrays (multidimensional arrays), objects, numbers, and strings.
Arrays allow you to store and process large lists of data, for example, a list of products in an online store or user profile data
Example of an array with different data types:
const mixedArray = [
42, // Number
"Hello", // String
true, // Boolean
null, // null
undefined, // undefined
{ name: "John", age: 30 }, // Object
[1, 2, 3], // Array
function() { return "Hi"; }, // Function
new Date(), // Date
/pattern/, // RegExp
Symbol('id'), // Symbol
123n, // BigInt
NaN, // NaN
Infinity // Infinity
];
console.log(mixedArray);// 1. Array of strings (names):
const names = ["Оля", "Андрій", "Марія", "Тарас", "Ірина"];
// 2. Array of numbers:
const ages = [18, 25, 30, 42, 57];
// 3. Mixed array (different data types):
const mixed = [ true, "JS", 2023, null, { skill: "coding" } ];
// 4. Array of objects:
const products = [
{ id: 1, name: "Ноутбук", price: 20000 },
{ id: 2, name: "Смартфон", price: 10000 },
{ id: 3, name: "Навушники", price: 800 }
];
// 5. Two-dimensional (nested) array:
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
Examples of arrays: strings, numbers, mixed arrays, arrays of objects, nested (two-dimensional) arrays
Values in an array can be modified: removed, replaced, or added. Changes can be made directly to the original array using special methods available in JavaScript for working with arrays. These methods are divided into two groups: those that modify the original array and those that process the array and return a new one, leaving the original array unchanged.
Methods that mutate the array
push()— adds one or more elements to the end of the array. Returns the new length of the array.pop()— removes the last element of the array and returns it.shift()— removes the first element of the array and returns it.unshift(…elements)— adds one or more elements to the beginning of the array.splice(start, deleteCount ,…items, …items,…items)— adds, removes, or replaces elements in the array at the specified index. Returns an array of removed elements.reverse()— reverses the order of elements in the array. Returns a reference to the modified array.sort(compareFunction)— sorts the elements of the array (by default as strings). Returns a reference to the sorted array.fill(value, start, end)— fills elements of the array from the start index to the end index with a single value.copyWithin(target, start, end)– copies a sequence of array elements within the array from positions[start, end)to positiontarget. Returns a reference to the modified array.
Methods that do not mutate the array
concat()— returns a new array that is the result of merging two or more arrays.slice()— returns a new array containing a copy of a portion of the original array.map()— returns a new array resulting from applying a function to each element of the original array.filter()— returns a new array containing elements that satisfy a condition.reduce()— returns a single value resulting from applying a function to each element of the array.reduceRight()— similar toreduce(), but processes the array from right to left.flat()— returns a new array with all sub-arrays flattened to the specified depth.flatMap()— combinesmap()andflat(), returns a new array.join()— returns a string that is the result of joining all array elements.toString()— returns a string representation of the array.indexOf()— returns the index of the first found element or-1if not found.lastIndexOf()— returns the index of the last found element or-1if not found.includes()— returnstrueorfalse, depending on whether the element exists in the array.find()— returns the first element that satisfies the condition, orundefined.findIndex()— returns the index of the first element that satisfies the condition, or-1.every()— returnstrueif all elements satisfy the condition.some()— returnstrueif at least one element satisfies the condition.
More about core array methods
Core methods and code examples for adding and removing elements
push(): Adds one or more elements to the end of the array and returns the new array length. Mutates the array.
pop(): Removes the last element from the array and returns the removed element. Mutates the array.
shift(): Removes the first element from the array and returns the removed element. Mutates the array.
unshift(): Adds one or more elements to the beginning of the array and returns the new array length. Mutates the array.
const numbers = [1, 2, 3]; // Add to the end numbers.push(4, 5); // numbers = [1, 2, 3, 4, 5] // Remove last const removed = numbers.pop(); // removed = 5, numbers = [1, 2, 3, 4] // Remove first numbers.shift(); // numbers = [2, 3, 4] // Add to the beginning numbers.unshift(0); // numbers = [0, 2, 3, 4]
How to create a copy of an array
Arrays are reference types in JavaScript. For example, if you do const arr2 = arr1;, it does not create a new array, but only a reference to the existing one.
If you need to work with an array without modifying it, you can use non-mutating methods or create a copy of the array using slice() or the spread operator (...):
const copy = [...arr]; // array copy
The slice() method allows you to create a new array that is a copy of part or all of the original array. It takes two arguments:
start (optional) — the index where copying begins (inclusive).
end (optional) — the index where copying ends (exclusive).
If no arguments are provided, slice() returns a full copy of the array.
Examples:
Full array copy
const arr = [1, 2, 3, 4, 5]; const copy = arr.slice(); // [1, 2, 3, 4, 5] console.log(copy); // [1, 2, 3, 4, 5] console.log(arr === copy); // false (these are different arrays)
Copy part of an array
const arr = [1, 2, 3, 4, 5]; const slicedCopy = arr.slice(2, 4); console.log(slicedCopy) //[ 3, 4 ];
Negative indices with one value
const arr = [1, 2, 3, 4, 5]; const part = arr.slice(-3); // [3, 4, 5] console.log(part); // [3, 4, 5]
Negative indices are counted from the end of the array.
Negative indices with two values
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']; console.log(animals.slice(2, -1)); // Array ["camel", "duck"]
Three ways to create an array
Array literal
// 'fruits' array created using array literal notation const fruits = ["Apple", "Banana"]; console.log(fruits.length); // 2
Array() constructor
// 'fruits' array created using array literal notation const fruits = ["Apple", "Banana"]; console.log(fruits.length); // 2
Methods like Array.from(), Array.of(), spread operator (...), split() for converting strings to arrays, map(), fill() and other non-mutating methods listed above.
Example using the from() method:
//From a string: const arr = Array.from("Hello");
console.log(arr); // ['H', 'e', 'l', 'l', 'o']
//From a set:
const set = new Set([1, 2, 3]);
const arr = Array.from(set); console.log(arr); // [1, 2, 3]
//From an array-like object:
const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 };
const arr = Array.from(arrayLike);
console.log(arr); // ['a', 'b', 'c']
//With a mapper function:
const arr = Array.from([1, 2, 3], x => x * 2);
console.log(arr); // [2, 4, 6]The Set object in the example above is a built-in JavaScript collection that represents a set of unique values. It is similar to an array but has several key differences. Let’s take a closer look at what Set is, how it works, and how it relates to objects and arrays.
Set is a collection that stores only unique values. This means it cannot contain duplicate elements. For example, if you add the number 5 twice, it will only be stored once.
Main characteristics:
- Uniqueness: All values in a
Setare unique. - Iterability:
Setcan be iterated using loops or methods likeforEach. - No indices: Unlike arrays,
Setdoes not have indices, so elements cannot be accessed by index. - Element operations:
Setprovides methods to add, remove, and check elements.
How to create a Set?
Set is created using the new Set() constructor. You can pass an iterable (for example, an array), and the Set will automatically include only unique elements from it.
For example, here the number 4 is added only once because Set stores only unique values:
const mySet = new Set([1, 2, 3, 4, 4, 5]);
console.log(mySet); // Set { 1, 2, 3, 4, 5 }Core methods and properties of Set
The Array.of() method
Creates an array from the passed arguments. It is useful when you need to create an array from a single number (unlike new Array(), which in that case creates an empty array with the specified length).
const arr = Array.of(5); console.log(arr); // [5]
Spread operator (...)
allows you to create a new array based on an existing array or another iterable object.
const original = [1, 2, 3]; const copy = [...original]; console.log(copy); // [1, 2, 3]
Merging arrays:
const arr1 = [1, 2]; const arr2 = [3, 4]; const combined = [...arr1, ...arr2]; console.log(combined); // [1, 2, 3, 4]
From an iterable object:
const str = "Hello"; const arr = [...str]; console.log(arr); // ['H', 'e', 'l', 'l', 'o']
The split() method
If you have a string that needs to be converted into an array, you can use the split() method.
const str = "apple,banana,orange";
const arr = str.split(',');
console.log(arr); // ['apple', 'banana', 'orange']Generating an array using Array() and map()
const arr = [1, 2, 3, 4, 5]; const part = arr.slice(-3); // [3, 4, 5] console.log(part); // [3, 4, 5]
If you need to create an array with a specific number of elements generated dynamically, you can use a combination of Array(), fill(), and map().
Array of numbers from 0 to 9:
const arr = Array(10).fill().map((_, index) => index); console.log(arr); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Array of squared numbers:
const arr = Array(5).fill().map((_, index) => (index + 1) ** 2); console.log(arr); // [1, 4, 9, 16, 25]
Generating an array using Array.from() and a mapper function
The Array.from() method also allows you to create an array using a mapper function that generates elements.
Array of numbers from 0 to 9:
const arr = Array.from({ length: 10 }, (_, index) => index);
console.log(arr); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
//creates an array of 10 elements where each element equals its index.
//_ is a convention for an unused argument (current element).
//index is the index of the current element, returned as the value.
//The function returns the value that will be placed in the array.Array of even numbers:
const arr = Array.from({ length: 5 }, (_, index) => index * 2);
console.log(arr); // [0, 2, 4, 6, 8]What does _ mean?
In JavaScript, _ is just a variable name. In this context, it is used to indicate an unused argument. This is a common practice to show that the value is intentionally ignored. For example: const func = (_, index) => index; This function takes two arguments but uses only index. The first argument (_) is ignored. If you don’t want to use _, you can simply omit the first argument: const arr = Array.from({ length: 10 }, (index) => index);
When to use an array literal vs constructor?
When to use array literal ([])?
- Most cases: array literal is the standard and most common way to create arrays. It is shorter, clearer, and less error-prone.
- When elements are known: if you know the elements in advance, array literal is the best choice.
- When creating an empty array: array literal is also suitable for creating an empty array.
- When readability matters: array literal is more intuitive and easier for other developers to understand.
When to use the Array() constructor?
When you need to create an array with a specific length:
- When you need a predefined length: the
Array()constructor is useful when you need to create an array with a specific number of empty elements (for later filling). - When creating arrays dynamically: if the length or elements are determined dynamically, the constructor can be helpful.
- When creating an array from a single number: in this case, it’s better to use
Array.of(), butArray()can also be used. - Legacy compatibility: in very old projects or for compatibility with older JavaScript versions, the constructor might be required.
Array iteration
Array iteration is used to process each element sequentially. It allows you to:
- Access or output array values (e.g.,
console.log()). - Modify each element if needed (e.g., multiply all numbers by 2).
- Collect data into a new structure (e.g., create a new array or calculate totals).
- Filter elements based on a condition.
- Transform data using methods like
map,reduce,filterto produce a new result.
Iteration enables almost any operation on array elements — from simple checks to complex data processing.
Array iteration examples
Loop for
This is the most basic method for iterating over an array. It allows you to define a counter, set conditions, and increment it.
Task: find all positive numbers in the array, multiply each by 2, and store the result in a new array.
const arr = [2, -1, 5, 0, 7];
const positiveDoubled = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] > 0) {
positiveDoubled.push(arr[i] * 2);
}
}
console.log(positiveDoubled);
// Result: [4, 10, 14]Explanation:
- Initialize an empty array
positiveDoubled. - Use a counter
ito iterate through all indices ofarr. - Check if the element (
arr[i]) is positive (> 0). - If yes, multiply it by 2 and add it (
push) to the new array. - In the end, we get an array of only positive numbers doubled.
Method map()
A method that creates a new array from the results of calling a function on every element of the original array.
Explanation:
map()applies a function to each element of the array and returns a new array with the results.- In this example, each element is multiplied by 2, resulting in a new array with doubled values.
- It is important that
map()does not modify the original array.
Method filter()
The filter() method creates a new array with all elements that pass the condition defined in a function.
Explanation:
filter()checks each element of the array against a condition.- In this case, we check whether a number is even using
num % 2 === 0. - The returned array contains only the elements that satisfy the condition.
Method reduce()
A method that reduces an array to a single value by executing a function for each element.
Explanation:
reduce()takes a function with two arguments:acc(accumulator): the value that is accumulated during iteration.num(current element): the current array element.- The second argument sets the initial value (e.g.,
0). - Each step adds the current element to the accumulator.
3. const values = Object.values(product); – We call the method Object.values(), which returns an array of all values of the product object.
4. const entries = Object.entries(product); – We call the method Object.entries(), which returns an array of pairs [key, value].
5. for (let [key, value] of entries) { ... } – We use the for...of loop to iterate over each element of the entries array. Since each element of the entries array is a small array with two elements [key, value], we use destructuring let [key, value] to immediately extract key and value into variables.
6. console.log(`Key: ${key}, Value: ${value}`); – On each iteration, we output a string showing the current key and its value.
As a result, in the console we will see:
Key: title, Value: Laptop
Key: price, Value: 1200
Key: currency, Value: USD
Key: inStock, Value: true
Note that object iteration in JavaScript can be done in several ways:
for...in (iterating over object properties),
Object.keys() / Object.values() / Object.entries() (getting arrays of keys/values/pairs),
for...of (iterating over array elements, if the object is an array or if you use Object.entries()).
Always keep in mind the type of data you are working with (string, number, boolean, array, or object). Depending on it, different methods and approaches will be used.
When working with nested structures (for example, an array inside an object, an object inside an array, or even an object inside another object), make sure you are accessing the correct level of nesting (using dot notation . or square brackets []).
Functions in arrays and objects in JavaScript: a detailed overview
In JavaScript, functions are first-class citizens, which means they can be:
Assigned to a variable:
let greet = function(name) {
console.log(`Привіт, ${name}!`);
};Passed as an argument to another function:
function callFunction(func) {
func();
}
callFunction(greet);Returned as a result of another function:
function createGreeter(greeting) {
return function(name) {
console.log(`${greeting}, ${name}!`);
};
}Functions in objects: methods
When a function is a property of an object, it is called a method. Methods allow objects to perform certain actions.
const person = {
firstName: "Іван",
lastName: "Петров",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
console.log(person.fullName()); // Виведе: "Іван Петров"this: Inside a method, this refers to the object itself. This allows the method to access other properties of the object.
Functions in arrays: array methods
Arrays in JavaScript are objects, so they also have their own methods. Array methods allow you to perform various operations on array elements, such as adding, removing, searching, and sorting.
const numbers = [1, 2, 3, 4, 5]; // Adding an element to the end of the array numbers.push(6); // Removing the last element numbers.pop(); // Sorting the array numbers.sort(); // Checking if an element exists in the array console.log(numbers.includes(3)); // Outputs: true
Functions as array elements
Although arrays usually store primitive values or other objects, they can also store functions:
const functions = [
function() { console.log("Функція 1"); },
function() { console.log("Функція 2"); }
];
functions[0](); // Outputs: "Функція 1"Key considerations when using functions in arrays and objects
- Execution context (
this): It is important to understand howthisworks inside functions, especially in object methods. - Binding context: To control the value of
this, you can usebind(),call(), andapply(). - Arrow functions: Arrow functions have special behavior regarding
this. - Using
thisin array methods: Some array methods, such asmap,filter, andreduce, take functions as arguments. In these functions,thismay refer to different objects depending on the context.
Why are arrow functions often used with array methods?
Arrow functions are especially convenient to use with array methods thanks to lexical this.
this: In functions passed to array methods, this usually refers to the global object. Arrow functions inherit this from the surrounding context, which allows you to use this from the object where the array method is called.
Conciseness: Arrow functions often make code more readable and compact.
Array methods that use functions:
map: Creates a new array by applying a function to each element.
filter: Creates a new array including only the elements for which the function returned true.
forEach: Executes a function for each array element.
find: Returns the first element for which the function returned true.
Conclusion
Arrays and objects are fundamental data structures in JavaScript that are used in almost every real-world project: from simple web pages to complex interfaces and server-side applications. Understanding their behavior, and knowing how to work with methods like push(), pop(), map(), filter() for arrays and Object.keys(), Object.values(), Object.entries() for objects helps you efficiently store, modify, and display data. It is also important to remember the differences between shallow and deep copying, as well as working with references, since in JavaScript arrays and objects are stored by reference.