Javascript Array methods
Arrays are a fundamental part of JavaScript, and knowing how to work with them efficiently is crucial for any developer. Whether you're adding, removing, or searching for elements, JavaScript provides powerful built-in functions like push() , pop() , shift() , unshift() , indexOf() , and lastIndexOf() to make array operations easier.
In this article, we'll learn these basic array functions, explain how they work, and when to use them. Ultimately, you'll gain a solid understanding of how to leverage them to write more accurate and efficient code.
Unshift() method
Adds new elements to the beginning of the array and returns the new length of the array.
Syntax
arrayName.ushift(element1, element2, element3)
This method can be used by writing the name of the array, then dot, then writing the name of the method (unshift) followed by parentheses, and inside these parentheses we pass the elements that we want to add to the beginning of the array as arguments.
Example:
let fruits = ['Blueberry', 'Pineapple'];
fruits.unshift('Strawberry', 'Banana'); // This line adds new elements to the beginning of the array. The elements are Strawberry and Banana.
console.log(fruits)
If we look at this example, we find that
- The first line, is an array containing two elements (Blueberry, Pineapple),
- The second line, I added two new elements (Strawberry, Banana) to the beginning of the array using the unshift method.
- The third line, prints the array in the console to find out the elements inside the array.
Push() method
Adds new elements at the end of the array, and returns the new length of the array.
Syntax
arrayName.push(element1, element2, element3)
This method can be used by writing the name of the array, then dot, then writing the name of the method (push) followed by parentheses, and inside these parentheses we pass the elements that we want to add to the end of the array as arguments.
Example:
let fruits = ['Blueberry', 'Pineapple'];
fruits.push('Strawberry', 'Banana'); // This line adds new elements to the end of the array. The two elements are strawberries and bananas.
console.log(fruits);
Shift() method
This method removes the first element in the array. And returns the deleted element.
Syntax
arrayName.shift()
This method can be used by writing the name of the array, then dot, then writing the name of the method (shift) followed by parentheses.
Note: This method does not take any parameters.
Example:
let fruits = ['Blueberry', 'Pineapple'];
fruits.shift(); // This line removes the first element from the array.
console.log(fruits);
If we look at this example, we find that
- The first line, is an array containing two elements (Blueberry, Pineapple),
- The second line, I remove the first element from the array using the shift method.
- The third line, prints the array in the console to find out the elements inside the array.
Pop() method
This method removes the last element in the array. And returns the deleted element.
Syntax
arrayName.pop()
This method can be used by writing the name of the array, then dot, then writing the name of the method (pop) followed by parentheses.
Note: This method does not take any parameters.
Example:
let fruits = ['Blueberry', 'Pineapple'];
fruits.shift(); // This line removes the last element from the array.
console.log(fruits);
IndexOf() method
This method searches for a specific value inside an array, Returns the first occurrence index of the value you are looking for. It returns -1 if the element is not present in the array.
Syntax
arrayName.indexOf(searchElement, fromIndex)
This method take two parameters
- The first parameter (Required) is searchElement: The value you want to search for in the array.
- The second parameter (optional) is fromIndex: The index from which to start the search. If you don't specify an index to start the search from, the search will start from index 0. Because the default value is 0
To use this method:
- Write the name of the array.
- then dot (.)
- then writing the name of the method (indexOf) followed by parentheses
- inside the parentheses we pass the value we want to search for inside the array as the first argument. and we pass The index from which to start the search as the second argument.
Example:
let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad'];
console.log(menu.indexOf('Meat')); // This line searches for a Meat value inside the array. It returns the index number of the element inside the array and prints it to the console.
If we look at this example, we find that:
- The first line of the code is an array containing several elements.
- The second line I use the indexOf method to look up the value of Meat inside the array, and return the index of the element.
Example:
let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad'];
console.log(menu.indexOf('Bread'));
If we look at this example, we find that:
- The first line of the code is an array containing several elements.
- The second line I use the indexOf method to look up the value of Bread inside the array, and return the index of the element.
- The result is -1 because the value I am looking for does not exist.
Example:
let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad', 'Rice'];
console.log(menu.indexOf('Rice'));
The result is 2 because returns the first occurrence index of the value you are looking for.
Example:
let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad', 'Rice'];
console.log(menu.indexOf('Rice', 3)); // This line searches for a Rice value inside the array. It returns the index of the element inside the array and prints it to the console. Search starts from index 3.
The result is 5 because I specified the index from which the search will start (index 3).
Example:
let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad', 'Rice'];
console.log(menu.indexOf('Rice', -1)); // This line searches for a Rice value inside the array. It returns the index number of the element inside the array and prints it to the console. Search starts from index -1.
Note: index -1 is the last element in the array.
let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad', 'Rice']
console.log(menu.indexOf('Bread') === -1);
lastIndexOf() method
This method searches for a specific value inside an array, starting from right to left, Returns the first occurrence index of the value you are looking for. It returns -1 if the element is not present in the array.
Syntax
arrayName.lastIndexOf(searchValue, fromIndex)
This method take two parameters:
- The first parameter (Required) is searchValue: The value you want to search for in the array.
- The second parameter (optional) is fromIndex: The index from which to start the search. If you don't specify an index to start the search from, the search will start from the last index in the array. (Default is 0 I think the Default is the last element)
To use this method:
- Write the name of the array.
- then dot (.)
- then writing the name of the method (lastIndexOf) followed by parentheses
- inside the parentheses we pass the value we want to search for inside the array as the first argument. and we pass The index from which to start the search as the second argument.
Example:
let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad', 'Rice'];
console.log(menu.lastIndexOf('Rice')); // This line searches for a Rice value inside the array. It returns the index of the element inside the array and prints it to the console.
Example:
let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad', 'Rice'];
console.log(menu.lastIndexOf('Rice', -2)); // This line searches for a Rice value inside the array. It returns the index of the element inside the array and prints it to the console.
Note:
-1
is the last element in the array or the first element from the right in the array.-2
is the second element from the right in the array.-3
is the third element from the right in the array and so on.
includes() method
The includes()
method is a built-in JavaScript function used to check for the existence of a specific element within the array.
- Returns
true
if the specified value you are looking for is found in the array. - Returns false if the value you are looking for is not found in the array.
Syntax
arrayName.includes(searchElement, fromIndex)
This method take two parameters:
- The first parameter is searchElement(Required): The value you are searching for in the array..
- The second parameter is fromIndex(optional): The index from which the search begins. The default is 0
To use this method:
- Start with the array name
- Then add a dot (.)
- then writing the name of the method (includes) followed by parentheses
- inside the parentheses we pass the element or value we want to search for as the first argument. And we pass the index we want to start the search from as the second argument
Example: Basic Usage:
let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad', 'Rice'];
console.log(menu.includes('Rice'); // Output: true
console.log(menu.includes('Bread'); // Output: false
If we look at this example, we find that:
- The first line of the code is an array containing several elements.
- The second line checks if
Rice
exists in the array using the includes method. The result is true because 'Rice' is in the array. - The third line checks for 'Bread'. The result is false because 'Bread' is not in the array.
Example: Using the fromIndex
parameter
let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad', 'Rice'];
console.log(menu.includes('Rice', 2); // Output: true
console.log(menu.includes('Chicken', 2); // Output: false
console.log(menu.includes('rice', 2); // Output: false
If we look at this example, we find that:
- The first line of the code is an array containing several elements.
menu.includes('Rice', 2)
: Searches forRice
starting from index2
using theincludes()
method. The result istrue
becauseRice
is found at index2
.menu.includes('Chicken', 2)
: Searches forChicken
starting from index2
using theincludes()
method. The result isfalse
becauseChicken
occurs before index2
.menu.includes('rice', 2)
: Searches forrice
(lowercase) starting from index2
using theincludes()
method. The result isfalse
because the search is case-sensitive.
Notes
- The
includes()
method is case-sensitive:Rice
andrice
are treated as different values. - If the
fromIndex
parameter is negative, the search starts from the array's length plus the negative value.
let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad', 'Rice']
if(menu.indexOf('Bread' === -1)) {
console.log('Sorry, bread is not on the menu');
}
// Sorry, bread is not on the menu
If the look at example, we found that:
- The first line of code is an array containing several elements.
- The second line is if that check from condition (
menu.indexOf('Bread' === -1)
) and returntrue
if the condition is correct. - The result is
Sorry, bread is not on the menu
Because theBread
value is not exist in the array.
reverse method
The reverse() method is a built-in function for arrays that reverses the order of the elements in an array in place. This means the original array is modified, and the elements are reordered such that the first element becomes the last, the second becomes before the last, and so on.
Syntax
arrayName.reverse();
Example:
let numbers = [1, 2, 3, 4, 5, 6];
console.log(numbers.reverse());
slice method
The slice() method is used to extract part of an array without modifying the original array.
In other words, it is used to create a copy of a part of an array without modifying the original array.
Syntax
arrayName.slice(startIndex, endIndex);
This method take two parameters:
The first parameter (optional) is start: The index at which the extraction begins.
If we don't write the startIndex, the default value will be set to 0 (the beginning of the array).
The second parameter (optional) is end: The index at which to end extraction (exclusive). The elements up to, but not including
If we don't write EndIndex, the default value is the length of the array (extracting all elements to the end).
Note If startIndex or endIndex is negative, counting will start from the end of the array. This means that -1 refers to the last element, -2 refers to the penultimate element and so on.
examples:
let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad'];
console.log(menu.slice()); // Output: Array ["Fish", "Chicken", "Rice", "Meat", "Salad"]
console.log(menu.slice(1)); // Output: Array ["Chicken", "Rice", "Meat", "Salad"]
console.log(menu.slice(1, 3)); // Output: Array ["Chicken", "Rice"], In this example, Starts at index 1 ('Chicken') and stops before index 3 ('Meat').
console.log(menu.slice(-2)); // Output: Array ["Meat", "Salad"]
console.log(menu.slice(1, -2)); // Output: Array ["Chicken", "Rice"]
console.log(menu.slice(-3, -1)); // Output: Array ["Rice", "Meat"]
splice method
The splice() method allows you to modify an array by adding, removing, or replacing elements at any position.
Syntax
array.splice(startIndex, deleteCount, item1, item2, ...)
Parameters
01. startIndex (required):
- The index at which to start changing the array
- Negative values count from the end of the array (-1 is last element)
02. deleteCount (optional):
- Number of elements to remove from the array
- If set to 0, no elements are removed
- If omitted, all elements from startIndex to end are removed
03. items (optional): Elements to add to the array starting at startIndex
Return Value
- 01. Returns an array containing the deleted elements
- 02. If no elements are removed, returns an empty array
Examples
01. Removing Elements
const fruits = ['apple', 'banana', 'orange', 'mango'];
// Remove 1 element at index 1
const removed = fruits.splice(1, 1);
console.log(fruits); // ['apple', 'orange', 'mango']
console.log(removed); // ['banana']
02. Adding Elements
const numbers = [1, 2, 5, 6];
// Add elements at index 2 without removing any
numbers.splice(2, 0, 3, 4);
console.log(numbers); // [1, 2, 3, 4, 5, 6]
*03. Replacing Elements
const colors = ['red', 'green', 'blue', 'yellow'];
// Replace 1 element at index 2 with 2 new elements
const replaced = colors.splice(2, 1, 'cyan', 'magenta');
console.log(colors); // ['red', 'green', 'cyan', 'magenta', 'yellow']
console.log(replaced); // ['blue']
**04. Using Negative Index
const letters = ['a', 'b', 'c', 'd'];
// Remove 1 element from the second-to-last position
letters.splice(-2, 1);
console.log(letters); // ['a', 'b', 'd']
Note splice() modifies the original array
Unlike slice(), which returns a portion of the array without modifying it, splice() changes the array and returns the removed elements
concat method
The concat() method is used to merge two or more arrays together in JavaScript. It doesn't modify the original arrays but instead returns a new array that contains the elements of the original arrays combined.
Syntax
const newArray = array1.concat(array2, array3, ...);
How It Works
- Creates a new array: The original arrays remain unchanged
- Combines elements: The new array contains elements from all concatenated arrays in order
- Accepts multiple arguments: You can pass one or more arrays or values to concatenate
Examples
Concatenating two arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = arr1.concat(arr2);
console.log(arr3); // Output: [1, 2, 3, 4, 5, 6]
Concatenating multiple arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [7, 8, 9];
const combined = arr1.concat(arr2, arr3);
console.log(combined); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
New values can be added directly
const arr1 = [1, 2];
const combined = arr1.concat(3, 4, 5);
console.log(combined); // Output: [1, 2, 3, 4, 5]
join method
The join() method is a built-in JavaScript array method that concatenates all elements of an array into a string, separated by a specified separator string.
Syntax
array.join([separator])
Parameters
separator
(optional): A string to separate each pair of adjacent elements of the array. If omitted, the array elements are separated with a comma (,
).
Return Value
A string with all array elements joined together.
Examples
Basic Usage
const fruits = ['Apple', 'Banana', 'Orange'];
console.log(fruits.join()); // Output: "Apple,Banana,Orange"
console.log(fruits.join(' - ')); // Output: "Apple - Banana - Orange"
With Different Separators
const numbers = [1, 2, 3];
console.log(numbers.join()); // Output: "1,2,3"
console.log(numbers.join('')); // Output: "123"
console.log(numbers.join(' + ')); // Output: "1 + 2 + 3"
With Empty Array
const empty = [];
console.log(empty.join('anything')); // Output: ""
With Different Data Types
const mixed = [1, 'two', true, null, undefined, {x: 1}];
console.log(mixed.join(' | '));
// Output: "1 | two | true | | | [object Object]"
Notes
- If an element is
undefined
,null
, or an empty array[]
, it's converted to an empty string. - Objects are converted to the string
"[object Object]"
. - The original array is not modified -
join()
returns a new string.