Array — is an ordered collection of elements in JavaScript that allows storing multiple values in a single variable. Array elements have numeric indices starting from zero.
Key features:
Array is a data structure in JavaScript that represents an ordered list of elements. Each element has its own index (position) in the array, starting from zero.
// Creating an empty array
const emptyArray = [];
// Creating an array with elements
const fruits = ["apple", "banana", "orange"];
// Accessing elements
console.log(fruits[0]); // "apple"
console.log(fruits[1]); // "banana"
console.log(fruits[2]); // "orange"
const numbers = [1, 2, 3, 4, 5];
const mixed = ["string", 42, true, null];
// Creating an empty array
const arr1 = new Array();
// Creating an array of specific length
const arr2 = new Array(5); // [empty × 5]
// Creating an array with elements
const arr3 = new Array(1, 2, 3); // [1, 2, 3]
// From string
const letters = Array.from("hello"); // ["h", "e", "l", "l", "o"]
// From NodeList
const divs = Array.from(document.querySelectorAll("div"));
// With transformation function
const squares = Array.from({length: 5}, (_, i) => i * i);
// [0, 1, 4, 9, 16]
// Creating array from arguments
const arr = Array.of(1, 2, 3); // [1, 2, 3]
const single = Array.of(5); // [5] (not [empty × 5])
// Copying array
const original = [1, 2, 3];
const copy = [...original]; // [1, 2, 3]
// Combining arrays
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2]; // [1, 2, 3, 4]
const fruits = ["apple", "banana", "orange"];
console.log(fruits.length); // 3
// Changing length
fruits.length = 2;
console.log(fruits); // ["apple", "banana"]
// Adding element through length
fruits[fruits.length] = "pear";
console.log(fruits); // ["apple", "banana", "pear"]
const numbers = [1, 2, 3];
// push() — adding to the end
numbers.push(4, 5);
console.log(numbers); // [1, 2, 3, 4, 5]
// unshift() — adding to the beginning
numbers.unshift(0);
console.log(numbers); // [0, 1, 2, 3, 4, 5]
// splice() — adding at any position
numbers.splice(3, 0, 2.5); // Insert 2.5 at position 3
console.log(numbers); // [0, 1, 2, 2.5, 3, 4, 5]
const fruits = ["apple", "banana", "orange", "pear"];
// pop() — removing last element
const last = fruits.pop();
console.log(last); // "pear"
console.log(fruits); // ["apple", "banana", "orange"]
// shift() — removing first element
const first = fruits.shift();
console.log(first); // "apple"
console.log(fruits); // ["banana", "orange"]
// splice() — removing elements
fruits.splice(1, 1); // Remove 1 element at position 1
console.log(fruits); // ["banana"]
const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
const fruits = ["apple", "banana", "orange"];
for (const fruit of fruits) {
console.log(fruit);
}
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((number, index) => {
console.log(`Element ${index}: ${number}`);
});
const fruits = ["apple", "banana", "orange"];
// ❌ Not recommended for arrays
for (const index in fruits) {
console.log(fruits[index]);
}
const numbers = [1, 2, 3, 4, 5];
// Multiplying by 2
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// Converting to objects
const users = ["Anna", "Boris", "Victor"];
const userObjects = users.map((name, index) => ({
id: index + 1,
name: name
}));
console.log(userObjects);
// [{id: 1, name: "Anna"}, {id: 2, name: "Boris"}, {id: 3, name: "Victor"}]
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Only even numbers
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4, 6, 8, 10]
// Filtering objects
const users = [
{ name: "Anna", age: 25 },
{ name: "Boris", age: 17 },
{ name: "Victor", age: 30 }
];
const adults = users.filter(user => user.age >= 18);
console.log(adults); // [{name: "Anna", age: 25}, {name: "Victor", age: 30}]
const numbers = [1, 2, 3, 4, 5];
// Sum of elements
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15
// Finding maximum value
const max = numbers.reduce((acc, num) => Math.max(acc, num));
console.log(max); // 5
// Grouping objects
const people = [
{ name: "Anna", city: "Moscow" },
{ name: "Boris", city: "SPb" },
{ name: "Victor", city: "Moscow" }
];
const groupedByCity = people.reduce((acc, person) => {
if (!acc[person.city]) {
acc[person.city] = [];
}
acc[person.city].push(person);
return acc;
}, {});
console.log(groupedByCity);
// {
// "Moscow": [{name: "Anna", city: "Moscow"}, {name: "Victor", city: "Moscow"}],
// "SPb": [{name: "Boris", city: "SPb"}]
// }
const users = [
{ id: 1, name: "Anna" },
{ id: 2, name: "Boris" },
{ id: 3, name: "Victor" }
];
// Finding element
const user = users.find(u => u.name === "Boris");
console.log(user); // { id: 2, name: "Boris" }
// Finding index
const index = users.findIndex(u => u.name === "Boris");
console.log(index); // 1
const fruits = ["apple", "banana", "orange"];
// Checking element existence
console.log(fruits.includes("banana")); // true
console.log(fruits.includes("pear")); // false
// Finding index
console.log(fruits.indexOf("banana")); // 1
console.log(fruits.indexOf("pear")); // -1
const numbers = [2, 4, 6, 8, 10];
// Check: is there at least one element > 5
console.log(numbers.some(num => num > 5)); // true
// Check: are all elements even
console.log(numbers.every(num => num % 2 === 0)); // true
class TodoList {
constructor() {
this.tasks = [];
this.nextId = 1;
}
addTask(text) {
const task = {
id: this.nextId++,
text: text,
completed: false,
createdAt: new Date()
};
this.tasks.push(task);
return task;
}
completeTask(id) {
const task = this.tasks.find(t => t.id === id);
if (task) {
task.completed = true;
}
}
removeTask(id) {
const index = this.tasks.findIndex(t => t.id === id);
if (index !== -1) {
this.tasks.splice(index, 1);
}
}
getCompletedTasks() {
return this.tasks.filter(task => task.completed);
}
getPendingTasks() {
return this.tasks.filter(task => !task.completed);
}
}
// Usage
const todoList = new TodoList();
todoList.addTask("Learn arrays");
todoList.addTask("Write code");
todoList.completeTask(1);
console.log(todoList.getCompletedTasks());
console.log(todoList.getPendingTasks());
const users = [
{ id: 1, name: "Anna", age: 25, city: "Moscow", salary: 50000 },
{ id: 2, name: "Boris", age: 30, city: "SPb", salary: 60000 },
{ id: 3, name: "Victor", age: 35, city: "Moscow", salary: 70000 },
{ id: 4, name: "Galina", age: 28, city: "Kazan", salary: 45000 }
];
// Average salary
const averageSalary = users.reduce((sum, user) => sum + user.salary, 0) / users.length;
console.log(`Average salary: ${averageSalary}`);
// Users from Moscow older than 30
const moscowSeniors = users
.filter(user => user.city === "Moscow")
.filter(user => user.age > 30);
// Sorting by salary
const sortedBySalary = [...users].sort((a, b) => b.salary - a.salary);
// Grouping by cities
const usersByCity = users.reduce((acc, user) => {
if (!acc[user.city]) {
acc[user.city] = [];
}
acc[user.city].push(user);
return acc;
}, {});
console.log(usersByCity);
class ShoppingCart {
constructor() {
this.items = [];
}
addItem(product, quantity = 1) {
const existingItem = this.items.find(item => item.product.id === product.id);
if (existingItem) {
existingItem.quantity += quantity;
} else {
this.items.push({ product, quantity });
}
}
removeItem(productId) {
this.items = this.items.filter(item => item.product.id !== productId);
}
updateQuantity(productId, quantity) {
const item = this.items.find(item => item.product.id === productId);
if (item) {
item.quantity = quantity;
}
}
getTotalPrice() {
return this.items.reduce((total, item) => {
return total + (item.product.price * item.quantity);
}, 0);
}
getTotalItems() {
return this.items.reduce((total, item) => total + item.quantity, 0);
}
clear() {
this.items = [];
}
}
// Usage
const cart = new ShoppingCart();
const products = [
{ id: 1, name: "Bread", price: 30 },
{ id: 2, name: "Milk", price: 60 },
{ id: 3, name: "Eggs", price: 80 }
];
cart.addItem(products[0], 2);
cart.addItem(products[1], 1);
cart.addItem(products[2], 1);
console.log(`Total cost: ${cart.getTotalPrice()} rub.`);
console.log(`Total items: ${cart.getTotalItems()}`);
const numbers = [1, 2, 3, 4, 5];
numbers[10] = 100;
console.log(numbers.length);
console.log(numbers[7]);
const arr = [1, 2, 3];
const result = arr.map(x => x * 2).filter(x => x > 4);
console.log(result);
console.log(arr);
const fruits = ["apple", "banana", "orange"];
fruits.forEach((fruit, index) => {
if (fruit === "banana") {
fruits.splice(index, 1);
}
});
console.log(fruits);
const colors = ["red", "green", "blue"];
// Destructuring
const [first, second, third] = colors;
console.log(first); // "red"
// Skipping elements
const [, , blue] = colors;
console.log(blue); // "blue"
// Rest elements
const [primary, ...secondary] = colors;
console.log(primary); // "red"
console.log(secondary); // ["green", "blue"]
// flat() — flattening nested arrays
const nested = [1, [2, 3], [4, [5, 6]]];
console.log(nested.flat()); // [1, 2, 3, 4, [5, 6]]
console.log(nested.flat(2)); // [1, 2, 3, 4, 5, 6]
// flatMap() — map + flat
const words = ["hello world", "how are you"];
const allWords = words.flatMap(phrase => phrase.split(" "));
console.log(allWords); // ["hello", "world", "how", "are", "you"]
const fruits = ["apple", "banana", "orange"];
// Access from end of array
console.log(fruits.at(-1)); // "orange"
console.log(fruits.at(-2)); // "banana"
// Equivalent to
console.log(fruits[fruits.length - 1]); // "orange"
// 1. Use const for arrays
const fruits = ["apple", "banana"];
fruits.push("orange"); // ✅ Can modify contents
// 2. Prefer array methods over loops
const doubled = numbers.map(x => x * 2); // ✅ Better
// than
const doubled2 = [];
for (let i = 0; i < numbers.length; i++) {
doubled2.push(numbers[i] * 2);
}
// 3. Use destructuring
const [first, ...rest] = array; // ✅ Readable
// 4. Check element existence
if (index >= 0 && index < array.length) {
console.log(array[index]);
}
// 5. Use spread for copying
const copy = [...original]; // ✅ Shallow copy
// ❌ Changing length to clear
array.length = 0; // Better: array.splice(0)
// ❌ Using for...in for arrays
for (const index in array) { /* ... */ }
// ❌ Direct array modification in forEach
array.forEach((item, index) => {
array.splice(index, 1); // Can skip elements
});
// ❌ Creating sparse arrays
const sparse = new Array(1000); // [empty × 1000]
// ❌ Mixing types unnecessarily
const mixed = [1, "string", {}, []]; // Makes typing difficult
// ❌ Problem
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((num, index) => {
if (num % 2 === 0) {
numbers.splice(index, 1); // Modifying array
}
});
// ✅ Solution
const numbers2 = [1, 2, 3, 4, 5];
const oddNumbers = numbers2.filter(num => num % 2 !== 0);
// ❌ Shallow copying of objects
const users = [{name: "Anna"}, {name: "Boris"}];
const copy = [...users];
copy[0].name = "Alice"; // Will change original too!
// ✅ Deep copying
const deepCopy = users.map(user => ({...user}));
// or
const deepCopy2 = JSON.parse(JSON.stringify(users));
// ❌ Forgot initial value
const sum = [].reduce((a, b) => a + b); // TypeError
// ✅ With initial value
const sum = [].reduce((a, b) => a + b, 0); // 0
Arrays are a fundamental data structure in JavaScript that:
Key characteristics:
Key methods:
push()
, pop()
, shift()
, unshift()
, splice()
, sort()
, reverse()
map()
, filter()
, reduce()
, find()
, includes()
, slice()
forEach()
, for...of
, regular for
Applications:
Best practices:
// Creation
const items = [];
// Adding
items.push(newItem);
// Transformation
const processed = items.map(transform).filter(condition);
// Search
const found = items.find(item => item.id === targetId);
Understanding arrays is the foundation for efficient data work in JavaScript!
Want more interview preparation articles? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪