Arrays in JavaScript
[Link]
An array is an ordered, zero-indexed collection of values that can store
multiple data types in a single variable. Arrays are technically objects and
come with a variety of built-in array methods (functions) that allow you to
manipulate, iterate over, and transform the data they hold.
let fruits = ['apple', 'banana', 'orange'];
let mixedData = [1, "hello", true];
Accessing Elements: numeric index starts from 0 for the first element.
[Link](fruits[0]); // Output: 'apple'
Length Property: returns the number of elements in the array
[Link]([Link]); // Output: 3
Modifying: Assign a value directly to an index.
fruits[1] = "pear" ;
[Link](fruits) // apple, pear, orange
Array methods generally fall into two categories: those that
modify the original array (mutator methods) and those that
return a new array or value without changing the original
(accessor/iteration methods).
Mutator Methods (Modify the Original Array):
splice(): Changes array content by removing, replacing, or
adding elements in place.
Accessor & Iteration Methods (typically return new
array/value):
concat(): Merges arrays to create a new array.
slice(): Returns a shallow copy of a portion of an array as a
new array.
1. Adding and Removing Elements (Mutating): These methods modify
the original array.
push(): Adds one or more elements to the end; returns the new length.
const arr = [1, 2];
[Link](3); // [1, 2, 3]
pop(): Removes the last element; returns the removed element.
[Link](); // returns 3; arr is now [1, 2]
unshift(): Adds one or more elements to the beginning; returns the new
length.
[Link](0); // [0, 1, 2]
shift(): Removes the first element; returns the removed
[Link](); // returns 0; arr is now [1, 2]
splice(): Adds, removes, or replaces elements at any index.
[Link](1, 0, "new");
// [1, "new", 2] (at index 1, delete 0, add "new")
2. Searching and Testing:
includes(): Checks if an array contains a value (returns
true/false).
[1, 2, 3].includes(2); // true
const activeStatus = ["online", "offline", "away"];
[Link]([Link]("online")); // true
indexOf(): Returns the first index of a specific value. Returns
-1, if element is not in the list.
["apple", "banana"].indexOf("banana"); // 1
3. Utility Methods(built-in) methods:
at(): Accesses elements using negative indices.
[10, 20, 30].at(-1); // 30 (last item)
join(): Converts an array into a string.
["a", "b", "c"].join("-"); // "a-b-c"
const tags = ["JS", "Web", "Dev"];
[Link]([Link](" | ")); // "JS | Web | Dev"
slice(): Returns a portion of the array without changing it.
[1, 2, 3, 4].slice(1, 3); // [2, 3]
concat(): Combines two or more arrays into a new
one without modifying the originals
const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = [Link](arr2); // [1, 2, 3, 4]
// Populating an array using a for loop:
const numbers = [];
for (let i = 0; i < 5; i++) {
[Link](i * 10); // Adds 0, 10, 20, 30, 40
}
[Link](numbers);
// Populating an array with random numbers:
const scores = new Array(5);
for (let i = 0; i < 5; i++) {
scores[i] = [Link]() * 100;
}
//Populating an array using a while loop
const collection = [];
let count = 0;
while (count < 3) {
[Link](`Item ${count}`);
count++;
}
Exercise: You have a list of items in a cart and need to calculate the
total price after applying a 15% tax to each item.
const cartPrices = [100, 50, 120];
let totalWithTax = 0;
for (let i = 0; i < [Link]; i++) {
const priceWithTax = cartPrices[i] * 1.15;
totalWithTax += priceWithTax;
}
[Link](`Total: $${[Link](2)}`);
// "Total: $310.50"
Exercise: Find the average of only the passing grades (60+).
const allScores = [45, 90, 80, 55, 100, 78];
let passingSum = 0;
let passingCount = 0;
for (let i = 0; i < [Link]; i++) {
if (allScores[i] >= 60) {
passingSum += allScores[i];
passingCount++;
}
}
const average = passingCount > 0 ? passingSum / passingCount : 0;
[Link](`Average of Passing Grades: ${[Link](1)}`);
// "87.0"
// Exercise: Removing duplicate elements from an array:
const userIds = [101, 102, 101, 105, 102, 108];
const uniqueIds = [];
for (let i = 0; i < [Link]; i++) {
// Check if the ID is already in our unique list
if ([Link](userIds[i]) === -1) {
[Link](userIds[i]);
}
}
[Link](uniqueIds); // [101, 102, 105, 108]