Introduction to JavaScript Array Methods
Let’s together discuss the JavaScript Array Methods along with their syntax and Array methods
toString() in JavaScript:
The toString() method is a JavaScript library function used to convert the given object to its corresponding string representation. toString in javascript can be used with numbers, strings, arrays, and objects.
Syntax of toString() in JavaScript
The following is the syntax of toString() in JavaScript:
Example of toString() in JavaScript
Let’s take a look at a basic example of how JavaScript toString() function is used: In this example, we are converting a number to the string value using the toString() function.
const myNum = 3
const str = myNum.toString()
console.log("Value of str variable is", str)
console.log("Type of str variable is", typeof str)
// Output
// Value of str variable is 3
// Type of str variable is string
join() in JavaScript:
The join() method returns an array as a string. The join() method does not change the original array. Any separator can be specified. The default is comma (,).
Syntax of join() in JavaScript
The following is the syntax of join() in JavaScript:
Example of join() in JavaScript
let message = ["JavaScript", "is", "fun."];
// join all elements of array using space
let joinedMessage = message.join(" ");
console.log(joinedMessage);
// Output: JavaScript is fun.
pop() in JavaScript:
The pop()
method removes the last element from an array and returns that element.
pop() Syntax
The syntax of the pop()
method is:
Example of pop() in JavaScript
let cities = ["Madrid", "New York", "Kathmandu", "Paris"];
// remove the last element
let removedCity = cities.pop();
console.log(cities) // ["Madrid", "New York", "Kathmandu"]
console.log(removedCity); // Paris
push() in JavaScript:
The push()
method adds zero or more elements to the end of the array.
push() Syntax
The syntax of the push()
method is:
arr.push(element1, element2, ..., elementN)
Example of push() in JavaScript
let city = ["New York", "Madrid", "Kathmandu"];
// add "London" to the array
city.push("London");
console.log(city);
// Output: [ 'New York', 'Madrid', 'Kathmandu', 'London' ]
shift() in JavaScript:
The shift()
method removes the first element from an array and returns that element.
shift() Syntax
The syntax of the shift()
method is:
Example of shift() in JavaScript
let languages = ["English", "Java", "Python", "JavaScript"];
// removes the first element of the array
let first = languages.shift();
console.log(first);
console.log(languages);
// Output: English
// [ 'Java', 'Python', 'JavaScript' ]
unshift() in JavaScript:
The unshift()
method adds one or more elements to the beginning of an array and returns the new length of the array.
unshift() Syntax
The syntax of the unshift()
method is:
arr.unshift(element1, element2, ..., elementN)
Example of unshift() in JavaScript
let languages = ["Java", "Python", "C"];
// add "JavaScript" at the beginning of the array
languages.unshift("JavaScript");
console.log(languages);
// Output: [ 'JavaScript', 'Java', 'Python', 'C' ]
delete(operator) in JavaScript:
Array elements can be deleted using the JavaScript operator delete. Using delete leaves undefined holes in the array
delete() Syntax
The syntax of the delete()
method is:
Example of delete() in JavaScript
let languages = ["English", "Java", "Python", "JavaScript"];
delete languages[1];
console.log(languages)
["English", <1 empty item>, "Python", "JavaScript"]
concat() in JavaScript:
The concat()
method returns a new array by merging two or more values/arrays.
concat() Syntax
The syntax of the concat()
method is:
arr.concat(value1, value2, ..., valueN)
Example of concat() in JavaScript
let primeNumbers = [2, 3, 5, 7]
let evenNumbers = [2, 4, 6, 8]
// join two arrays
let joinedArrays = primeNumbers.concat(evenNumbers);
console.log(joinedArrays);
/* Output:
[
2, 3, 5, 7,
2, 4, 6, 8
]
*/
sort() in JavaScript:
The sort()
method sorts the items of an array in a specific order (ascending or descending).
sort() Syntax
The syntax of the sort()
method is:
arr.sort(compareFunction)
Example of sort() in JavaScript
let city = ["California", "Barcelona", "Paris", "Kathmandu"];
// sort the city array in ascending order
let sortedArray = city.sort();
console.log(sortedArray);
// Output: [ 'Barcelona', 'California', 'Kathmandu', 'Paris' ]
splice() in JavaScript:
The splice()
method modifies an array (adds, removes or replaces elements).
splice() Syntax
The syntax of the splice()
method is:
arr.splice(start, deleteCount, item1, ..., itemN)
Example of splice() in JavaScript
let prime_numbers = [2, 3, 5, 7, 9, 11];
// replace 1 element from index 4 by 13
let removedElement = prime_numbers.splice(4, 1, 13);
console.log(removedElement);
console.log(prime_numbers);
// Output: [ 9 ]
// [ 2, 3, 5, 7, 13, 11 ]
slice() in JavaScript:
The slice()
method returns a shallow copy of a portion of an array into a new array object.
slice() Syntax
The syntax of the slice()
method is:
Example of slice() in JavaScript
let numbers = [2, 3, 5, 7, 11, 13, 17];
// create another array by slicing numbers from index 3 to 5
let newArray = numbers.slice(3, 6);
console.log(newArray);
// Output: [ 7, 11, 13 ]
reverse() in JavaScript:
The reverse()
method returns the array in reverse order.
reverse() Syntax
The syntax of the reverse()
method is:
Example of reverse() in JavaScript
let numbers = [1, 2, 3, 4, 5];
// reversing the numbers array
let reversedArray = numbers.reverse();
console.log(reversedArray);
// Output: [ 5, 4, 3, 2, 1 ]
isArray() in JavaScript:
The isArray()
method checks whether the passed argument is an array or not.
isArray() Syntax
The syntax of the isArray()
method is:
Example of isArray() in JavaScript
let numbers = [1, 2, 3, 4];
// checking whether numbers is an array or not
console.log(Array.isArray(numbers));
let text = "JavaScript";
// checking whether text is an array or not
console.log(Array.isArray(text));
// Output:
// true
// false
indexOf() in JavaScript:
The indexOf()
method returns the first index of occurance of an array element, or -1 if it is not found.
indexOf() Syntax
The syntax of the indexOf()
method is:
arr.indexOf(searchElement, fromIndex)
Example of indexOf() in JavaScript
let languages = ["Java", "JavaScript", "Python", "JavaScript"];
// get the index of the first occurrence of "JavaScript"
let index = languages.indexOf("JavaScript");
console.log(index);
// Output: 1
lastindexOf() in JavaScript:
The lastIndexOf()
method returns the index of the last occurrence of a specified element in the array.
lastindexOf() Syntax
The syntax of the lastindexOf()
method is:
arr.lastIndexOf(searchElement, fromIndex)
Example of lastindexOf() in JavaScript
let priceList = [10, 8, 2, 31, 10, 31, 65];
// finding the index of the last occurence of 31
let lastIndex = priceList.lastIndexOf(31);
console.log(lastIndex);
// Output: 5
find() in JavaScript:
The find()
method returns the value of the first array element that satisfies the provided test function.
find() Syntax
The syntax of the find()
method is:
arr.find(callback(element, index, arr),thisArg)
Example of find() in JavaScript
let numbers = [1, 3, 4, 9, 8];
// function to check even number
function isEven(element) {
return element % 2 == 0;
}
// get the first even number
let evenNumber = numbers.find(isEven);
console.log(evenNumber);
// Output: 4
findIndex() in JavaScript:
The findIndex()
method returns the index of the first array element that satisfies the provided test function or else returns -1.
findIndex() Syntax
The syntax of the findIndex()
method is:
arr.findIndex(callback(element, index, arr),thisArg)
Example of findIndex() in JavaScript
// function that returns odd number
function isOdd(element) {
return element % 2 !== 0;
}
// defining an array of integers
let numbers = [2, 8, 1, 3, 4];
// returns the index of the first odd number in the array
let firstOdd = numbers.findIndex(isOdd);
console.log(firstOdd);
// Output: 2
includes() in JavaScript:
The includes()
method checks if an array contains a specified element or not.
includes() Syntax
The syntax of the includes()
method is:
arr.includes(valueToFind, fromIndex)
Example of includes() in JavaScript
// defining an array
let languages = ["JavaScript", "Java", "C"];
// checking whether the array contains 'Java'
let check = languages.includes("Java");
console.log(check);
// Output: true
entries() in JavaScript:
The entries()
method returns a new Array Iterator object containing key/value pairs for each array index.
entries() Syntax
The syntax of the entries()
method is:
Example of entries() in JavaScript
// defining an array named alphabets
const alphabets = ["A", "B", "C"];
// array iterator object that contains
// key-value pairs for each index in the array
let iterator = alphabets.entries();
// iterating through key-value pairs in the array
for (let entry of iterator) {
console.log(entry);
}
// Output:
// [ 0, 'A' ]
// [ 1, 'B' ]
// [ 2, 'C' ]
every() in JavaScript:
The every()
method checks if all the array elements pass the given test function.
every() Syntax
The syntax of the every()
method is:
arr.every(callback(currentValue), thisArg)
Example of every() in JavaScript
// function that checks whether
// the age is 18 or above
function checkAdult(age) {
return age >= 18;
}
const ageArray = [34, 23, 20, 26, 12];
//checks if all the array elements
// pass the checkAdult() function
let check = ageArray.every(checkAdult);
// Output: false
some() in JavaScript:
The some()
method tests whether any of the array elements pass the given test function.
some() Syntax
The syntax of the some()
method is:
arr.some(callback(currentValue), thisArg)
Example of some() in JavaScript
// a test function: returns an even number
function isEven(element) {
return element % 2 === 0;
}
// defining an array
let numbers = [1, 3, 2, 5, 4];
// checks whether the numbers array contain at least one even number
console.log(numbers.some(isEven));
// Output: true
copywithin() in JavaScript:
The copyWithin()
method copies array elements from one position to another in the given array.
copywihin() Syntax
The syntax of the copywithin()
method is:
arr.copyWithin(target, start, end)
Example of copywithin() in JavaScript
let words = ["apple", "ball", "cat", "dog"];
// copies element from index 0 to index 3
words.copyWithin(3, 0);
// modifies the original array
console.log(words);
// Output:
// [ ''apple'', ''ball'', ''cat'', ''apple'' ]
valueOf() in JavaScript:
The valueOf()
method returns the array itself and this method does not change the original array.
valueOf() Syntax
The syntax of the valueOf()
method is:
Example of valueOf() in JavaScript
var Student = { Name: 'Ali', RollNo: '234' }
console.log(Student.valueOf())
//Output
{ Name: 'Ali', RollNo: '234' }
forEach() in JavaScript:
The forEach()
method executes a provided function for each array element.
forEach() Syntax
The syntax of the forEach()
method is:
arr.forEach(callback(currentValue), thisArg)
Example of forEach() in JavaScript
let numbers = [1, 3, 4, 9, 8];
// function to compute square of each number
function computeSquare(element) {
console.log(element * element);
}
// compute square root of each element
numbers.forEach(computeSquare);
/* Output:
1
9
16
81
64
*/
filter() in JavaScript:
The filter()
method returns a new array with all elements that pass the test defined by the given function.
filter() Syntax
The syntax of the filter()
method is:
arr.filter(callback(element), thisArg)
Example of filter() in JavaScript
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// function to check even numbers
function checkEven(number) {
if (number % 2 == 0)
return true;
else
return false;
}
// create a new array by filter even numbers from the numbers array
let evenNumbers = numbers.filter(checkEven);
console.log(evenNumbers);
// Output: [ 2, 4, 6, 8, 10 ]
reduce() in JavaScript:
The reduce()
method executes a reducer function on each element of the array and returns a single output value.
reduce() Syntax
The syntax of the reduce()
method is:
arr.reduce(callback(accumulator, currentValue), initialValue)
Example of reduce() in JavaScript
const message = ["JavaScript ", "is ", "fun."];
// function to join each string elements
function joinStrings(accumulator, currentValue) {
return accumulator + currentValue;
}
// reduce join each element of the string
let joinedString = message.reduce(joinStrings);
console.log(joinedString);
// Output: JavaScript is fun.
reduceRight() in JavaScript:
The reduceRight()
method reduces the array to a single value by executing a callback function on two values of the array (from right to left).
reduceRight() Syntax
The syntax of the reduceRight()
method is:
arr.reduceRight(callback(accumulator, currentValue), initialValue)
Example of reduceRight() in JavaScript
let numbers = [1, 2, 3, 4];
// function that adds last two values of the numbers array
function sum_reducer(accumulator, currentValue) {
return accumulator + currentValue;
}
// returns a single value after reducing the numbers array
let sum = numbers.reduceRight(sum_reducer);
console.log(sum);
// Output: 10
from() in JavaScript:
The from()
method creates a new array from any array-like or iterable object.
from() Syntax
The syntax of the from()
method is:
Array.from(arraylike, mapFunc, thisArg)
Example of from() in JavaScript
// creating a new array from string
let newArray = Array.from("abc");
console.log(newArray);
// Output:
// [ 'a', 'b', 'c' ]
Thanks for reading this article, If you find it useful please share it with your friends and keep visiting for more amazing content.