Array Methods in Javascript
To help you perform common tasks efficiently, JavaScript provides a wide variety of array methods. These methods allow you to add, remove, find, and transform array elements with ease.
Array length
The length property is the standard way to find the number of elements in a JavaScript array. It returns an integer representing the total number of slots in the array.To get the size of an array, use the .length property. Do not use parentheses because it is a property, not a method.
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.length); // Output: 3
const fruits = ['apple', 'banana'];
if (fruits.length === 0) {
console.log("Array is empty");
} else {
console.log("Array has items inside it!");
}
// Output: Array has items inside it!
const numbers = [10, 20, 30, 40];
numbers.length = 2;
console.log(numbers); // Output: [10, 20]
Extending an array: Increasing the length property adds empty slots (not undefined values) to the end of the array.
const items = ['A'];
items.length = 3;
console.log(items); // Output: ['A', <2 empty items>]
Array toString()
It converts a JavaScript array into a single, comma-separated string containing all its elements.This method takes no arguments and always has a Return Type of a String containing all elements separated by commas. It is compatible with any data type inside the array; numbers, booleans, and strings convert cleanly to text.
const fruits = ["Apple", "Banana", "Orange"];
const result = fruits.toString();
console.log(result);
//Apple,Banana,Orange
// Array containing numbers, strings, and mixed text
const mixedArray = [100, "Apple", 250, "Banana", 12.5, "Orange"];
// Convert to string
const result = mixedArray.toString();
console.log(result);//100,Apple,250,Banana,12.5,Orange
console.log(typeof result);// string
No Modification: It does not change the original array. It returns a brand-new string.
No Parameters: The method accepts zero arguments.
Array join() Method
It creates and returns a new string by concatenating all of the elements in this array, separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.The join() method always returns a string data type.Even if your array contains only numbers, booleans, or objects, the final output will always be converted into a single primitive string text.
Return Value: A brand-new string.
Original Array: It remains completely unchanged (pure method).
Default Behavior: If you provide no separator, it defaults to a comma (,).
const elements = ['Fire', 'Air', 'Water'];
// 1. No argument (defaults to comma)
console.log(elements.join());
// 2. Custom separator (comma and space)
console.log(elements.join(', '));
// 3. Empty string separator (joins directly)
console.log(elements.join(''));
// 4. Custom word or character separator
console.log(elements.join(' and '));
//Fire,Air,Water
Fire, Air, Water
FireAirWater
Fire and Air and Water
null and undefined handling: If any element in the array is null or undefined, join() converts it into an empty string "" instead of printing "null" or "undefined".
const mixed = ['Hello', null, 'World', undefined];
console.log(mixed.join('-')); //Hello--World-
console.log([1, , 3].join(','));//1,,3
Array at()
It is an method takes an integer value and returns the item at that index, allowing for both positive and negative integers.The primary advantage of at() is that it simplifies negative indexing, allowing you to count elements backward from the end of an array.
1.Accessing the Last Element (The at() Advantage)
Instead of using the bulky bracket notation to calculate the final index, you can use -1.
const colors = ['red', 'green', 'blue', 'yellow'];
// Old bracket way
console.log(colors[colors.length - 1]); // yellow
// New at() way
console.log(colors.at(-1)); // yellow
console.log(colors.at(-2)); // green
2. Positive vs. Negative Indexing
const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.at(0)); // apple (First item)
console.log(fruits.at(1)); // banana (Second item)
console.log(fruits.at(-3)); // apple (Third from the end)
console.log(fruits.at(10)); // undefined (Out of bounds)
Array pop()
It is an method in JavaScript removes the last element from an array and returns that element.This is a mutating method, meaning it modifies the original array directly by changing its contents and decreasing its length property by one.
Parameters: None.
Return Value: The removed element from the array. If the array is empty, it returns undefined.
// Initialize an array
const frameworks = ["React", "Vue", "Angular"];
// Remove the last item
const removedFramework =frameworks.pop();
console.log(removedFramework); // Output: Angular (the removed element)
console.log(frameworks); // Output: ['React', 'Vue'] (the original array is mutated)
console.log(frameworks.length); // Output: 2 (the length decreased by 1)
Empty Arrays: Calling pop() on an empty array does not throw an error; it simply returns undefined and leaves the length at 0.
const emptyArray = [];
console.log(emptyArray.pop()); // undefined
Array push()
It is an method adds one or more elements to the end of an array and returns the new length of that array. It is a destructive method, meaning it mutates (changes) the original array directly.
Returns a number: It does not return the updated array; it returns the updated length integer.
Appends multiple items: You can pass multiple values at once as individual arguments.
const fruits = ['apple', 'banana'];
const newLength = fruits.push('orange');
console.log(fruits); // ['apple', 'banana', 'orange']
console.log(newLength); // 3
const numbers = [1, 2];
numbers.push(3, 4, 5);
console.log(numbers); // Output: [1, 2, 3, 4, 5]
Array shift()
It is an method in JavaScript removes the very first element from an array and returns that removed element. This method permanently changes (mutates) the original array by shifting all remaining items down by one index and decreasing the array's length by one.
Return Value: It extracts and returns the item from index 0. If you call it on an empty array, it leaves the array unchanged and returns undefined.
Array Mutation: It modifies the array in place.
const fruits = ["Apple", "Banana", "Cherry"];
// Remove the first item
const firstFruit = fruits.shift();
console.log(firstFruit); // Output: Apple
console.log(fruits); // Output: ['Banana', 'Cherry']
Array unshift()
The unshift() method adds one or more elements to the beginning of an array and returns the new length of that array. It modifies (mutates) the original array directly by shifting existing elements to higher indexes.
Mutates the Original Array: **The original array is overwritten.
**Returns a Number: The method returns the updated length property of the array.
const fruits = ['apple', 'banana'];
const newLength = fruits.unshift('orange');
console.log(fruits); // Output: ['orange', 'apple', 'banana']
console.log(newLength); // Output: 3
Adding Multiple Elements At Once
When you pass multiple arguments, they are added together at the start, maintaining their original sequence.
const numbers = [3, 4];
numbers.unshift(1, 2);
console.log(numbers); // Output: [1, 2, 3, 4]
Array.isarray()
Array.isArray() is a built-in static method in JavaScript used to determine whether a passed value is an array. It returns true if the value is an array, and false if it is not.
// Returns true
console.log(Array.isArray([]));
console.log(Array.isArray([1, 2, 3]));
console.log(Array.isArray(new Array()));
// Returns false
console.log(Array.isArray({}));
console.log(Array.isArray("Hello"));
console.log(Array.isArray(42));
console.log(Array.isArray(undefined));
Array delete()
It is a delete operator, but using it on arrays is generally discouraged because it leaves empty (undefined) holes and does not change the array's length.To properly remove elements and shift the remaining items, you should use built-in array methods like splice() or filter().
const fruits = ['apple', 'banana', 'orange'];
delete fruits[1];
console.log(fruits); // ['apple', <1 empty item>, 'orange']
console.log(fruits.length); // 3 (Length does NOT change)
Array concat()
It is a built-in JavaScript method used to merge two or more arrays or values into a single, brand-new array. Crucially, this method does not change the original arrays; instead, it returns a shallow copy containing the combined elements.
Parameters: Arrays and/or individual values to combine.
Return value: A completely new array instance.
const arr1 = ["Cecilie", "Lone"];
const arr2 = ["Emil", "Tobias", "Linus"];
console.log(arr1.concat(arr2));//[ 'Cecilie', 'Lone', 'Emil', 'Tobias', 'Linus' ]
Array copyWithin()
It modifies an array in place by copying a section of it to another position within the same array. It never changes the length of the array.
Syntax
array.copyWithin(target, start, end)
target → The index where the copied elements will be pasted.
start → The index from which elements will be copied.
end → The index up to which elements will be copied (exclusive, not included).
const numbers = [1, 2, 3, 4, 5];
// Copy everything from index 0 and paste it starting at index 3
numbers.copyWithin(3);
console.log(numbers); // Output: [1, 2, 3, 1, 2]
// (Notice the length is still 5; the last two numbers were cut off)
Specifying a start Position
const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
// Copy from index 3 to the end, paste starting at index 0
fruits.copyWithin(0, 3);
console.log(fruits); // ['date', 'elderberry', 'cherry', 'date', 'elderberry']
Specifying start and end Range
Remember that the end index is exclusive.
const letters = ['a', 'b', 'c', 'd', 'e'];
// Copy elements from index 1 up to (but not including) index 3 -> ['b', 'c']
// Paste them starting at index 3
letters.copyWithin(3, 1, 3);
console.log(letters); // Output: ['a', 'b', 'c', 'b', 'c']
target = 3 → Paste starting at index 3
start = 1 → Copy starting from index 1
end = 3 → Copy up to index 3 (index 3 not included).So only elements at index 1 and 2 ('b' and 'c') are copied and pasted starting at index 3.
Using Negative Indices
const items = [10, 20, 30, 40, 50];
// Target: -2 (index 3)
// Start: -4 (index 1)
// End: -1 (index 4, exclusive)
items.copyWithin(-2, -4, -1);
console.log(items);// Output: [10, 20, 30, 20, 30]
Array flat()
Flattening an array is the process of reducing the dimensionality of an array.Flattening is useful when you want to convert a multi-dimensional array into a one-dimensional array.The flat() method creates a new array with sub-array elements concatenated to a specified depth.
Syntax
const newArray = arr.flat(depth);
const myArr = [[1,2],[3,4],[5,6]];
console.log(myArr.flat());//[ 1, 2, 3, 4, 5, 6 ]
Array slice()
It is a built-in JavaScript method that extracts a section of an array and returns it as a brand-new array. Crucially, it is a non-destructive method, meaning the original array remains completely unchanged.
Syntax
array.slice(start, end)
start (Optional): The zero-based index where extraction begins. Defaults to 0.
end (Optional): The index before which to end extraction. The element at this index is excluded. Defaults to the end of the array.
Extracting a Sub-array (Middle Portion)
Provide both start and end arguments to get a clean slice. Remember that the end index is exclusive.
const colors = ['red', 'green', 'blue', 'yellow', 'purple'];
const favorites = colors.slice(1, 4);
console.log(favorites); // ['green', 'blue', 'yellow']
console.log(colors); // ['red', 'green', 'blue', 'yellow', 'purple'] (Unchanged)
const numbers = [10, 20, 30, 40, 50];
const remaining = numbers.slice(2);
console.log(remaining); // [30, 40, 50]
Using Negative Indices
const animals = ['cat', 'dog', 'bird', 'fish'];
// Get the last two elements
console.log(animals.slice(-2)); // ['bird', 'fish']
// Mix positive and negative indices (start at index 1, stop 1 element before the end)
console.log(animals.slice(1, -1)); // ['dog', 'bird']
Array splice()
It is a method in JavaScript is a built-in function used to modify the contents of an array by removing, replacing, or adding elements in place.
Syntax
array.splice(start, deleteCount, item1, item2, /* ... */ itemN)
Adding Elements (Without Deleting)
let fruits = ['Apple', 'Date'];
// At index 1, delete 0 items and insert 'Banana' and 'Cherry'
fruits.splice(1, 0, 'Banana', 'Cherry');
console.log(fruits); // Output: ['Apple', 'Banana', 'Cherry', 'Date']
Removing Elements
To remove elements, provide the starting index and how many items to delete.
let fruits = ['Apple', 'Banana', 'Cherry', 'Date'];
// Remove 2 elements starting at index 1 ('Banana' and 'Cherry')
let removed = fruits.splice(1, 2);
console.log(fruits); // Output: ['Apple', 'Date']
console.log(removed); // Output: ['Banana', 'Cherry'] (The deleted items)
Replacing Elements
let fruits = ['Apple', 'Banana', 'Cherry', 'Date'];
// At index 1, remove 2 elements and insert 'Mango'
fruits.splice(1, 2, 'Mango');
console.log(fruits);
// Output: ['Apple', 'Mango', 'Date']
Removing Everything from an Index
let fruits = ['Apple', 'Banana', 'Cherry', 'Date'];
// Drop everything starting from index 2
fruits.splice(2);
console.log(fruits);
// Output: ['Apple', 'Banana']
Array toSpliced()
It is an method is a modern JavaScript feature (introduced in ES2023) that allows you to delete, insert, or replace elements in an array without modifying the original array.
Deleting Elements
const numbers = [10, 20, 30, 40, 50];
// Remove 2 elements starting at index 1
const modified = numbers.toSpliced(1, 2);
console.log(modified); // [10, 40, 50]
console.log(numbers); // [10, 20, 30, 40, 50] (Original is completely untouched)
Inserting Elements
const fruits = ['apple', 'banana'];
// Insert 'cherry' and 'date' at index 1
const modifiedFruits = fruits.toSpliced(1, 0, 'cherry', 'date');
console.log(modifiedFruits); // ['apple', 'cherry', 'date', 'banana']
Replacing Elements
const letters = ['a', 'b', 'c', 'd'];
// Replace 'b' and 'c' (index 1) with 'X' and 'Y'
const updatedLetters = letters.toSpliced(1, 2, 'X', 'Y');
console.log(updatedLetters); // ['a', 'X', 'Y', 'd']
Array Iterations
Array forEach
It is an method executes a provided callback function once for each element in an array in ascending order.
const fruits = ["Apple", "Mango", "Orange"];
fruits.forEach(function(fruit) {
console.log(fruit);
});//Apple
Mango
Orange
const fruits = ["Apple", "Mango", "Orange"];
fruits.forEach(function(fruit, index) {
console.log(index, fruit);
});//0 Apple
1 Mango
2 Orange
References
1.https://www.geeksforgeeks.org/javascript/javascript-array-methods/
2.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
Top comments (0)