Arrays are special objects in JavaScript that we use to store collections of values. JavaScript offers several built-in methods and properties that allow us to manipulate the arrays. In this tutorial, let us explore all the JavaScript array methods with an example of each.
Following are all the methods available on arrays in JavaScript
The IsArray method allows you to check whether a given value is an array. It returns a true if the value is an array and a false if it is not.
IsArray is the preferred method over instanceOf because it works across realms.
isArray method added in the ES5 version of JavaScript. Hence will not work in older browsers.
The code below uses the isArray method to check if the given value is an array.
let arr = [1,2,3]
console.log(Array.isArray(arr)); //true
arr = new Array(5)
console.log(Array.isArray(arr)); //true
let obj= {}
console.log(Array.isArray(obj)); //false
//Typed Arrays are not arrays. They are objects
let int16Arr = new Int16Array(2);
console.log(Array.isArray(int16Arr)); //false
The Array from method creates a new array from an iterable object or array-like object.
An “iterable object” is anything we can iterate over item by item. For example, arrays, objects, and strings are iterable in JavaScript.
An array-like object is an object which looks like an array but is not an array.
An array-like object is an object which looks like an array but is not an array.
An object, if it has
For Example, the arrLike object below looks like an array with integer property names and a length property
We can easily convert array-like objects using the from method.
You can read more from the tutorial array from in Javascript.
The of is a static method that creates a new Array instance from the arguments we pass to it, regardless of the number or type of the arguments.
The syntax of of method is as follows
Array.of(element0, element1, /* … ,*/ elementN)
Examples of array of method.
arr = Array.of('foo', 2, 'bar', true)
console.log(arr); //[ 'foo', 2, 'bar', true ]
arr = Array.of(2)
console.log(arr); //[2]
arr = Array.of()
console.log(arr); //[]
It is very similar to an Array constructor, with one difference. The new Array(5) will create an array with five empty elements, while Array.of(5) will create an array with one element of value 5
arr= new Array(5)
console.log(arr) //[ <5 empty items> ]
arr = Array.of(5)
console.log(arr); //[5]
The at method allows us to read an element from the array. It takes an integer (both positive and negative) value and returns the element at that index. The array is read backward from the end if we provide a negative integer.
In the code below, arr.at(1) reads the value at index 1. While arr.at(-1) will read the value at index four i.e, (arr.length-1)
const arr = [1, 2, 3, 4, 5];
console.log(arr.at(1)) //2 Value at index 1
console.log(arr.at(-1)) //5 Value at index 4 (5 - 1)
The array push method adds new elements to the end of an array. It takes the element to be added as an argument and returns the array’s new length. This method can push scalar values, objects, or another array to an array.
Syntax of the push method is as follows
push(element0, element1, /* … ,*/ elementN)
Here element0, element1, …, elementN are the elements you want to add to the end of the array. You can provide any number of items separated by a comma.
.The following example, appends multiple elements to the array by supplying multiple items separated by a comma to the push method.
.
let numbers=[1,2,3,4]
numbers.push(5,6,7) //pushing 5,6,7 to numbers array
console.log(numbers) //[ 1, 2, 3, 4, 5, 6, 7 ]
array push method in JavaScript
The pop method removes and returns the array’s last element. If the array is empty, it will do nothing but return undefined.
It mutates the array and changes its length.
Syntax of the array.pop method is follows
array.pop()
In the following code. we create an array of numbers and then call the pop() method on it. The method removes the last element from the array, the number 5, and returns its value. We store the returned value in a variable named lastNumber. Finally, we log the modified array and the removed value to the console.
You can read more about from the tutorial array pop method in JavaScript
The array Unshift method is a built-in JavaScript method that adds new elements to the beginning of an array. It takes the element to be added as an argument and returns the array’s new length. This method can insert scalar values, objects, or another array into an array.
The syntax for the unshift() method is as follows:
array.unshift(element0, element1, /* … ,*/ elementN)
The code below inserts multiple elements to the numbers array.
let numbers=[5,6,7]
//inserting multiple items at the start of numbers array
numbers.unshift(1,2,3,4)
console.log(numbers) //[ 1, 2, 3, 4, 5, 6, 7 ]
The array shift method removes and returns the first element from the array. If the array is empty, it will do nothing but return undefined.
It mutates the array and changes its length.
The syntax of the array.shift method is as follows:
array.shift()
It does not take any arguments.
In the following example, we have an array of numbers. We call the shift method on it. It removes the first element, number 1, from the array and returns its value.
let numbers = [1, 2, 3, 4, 5];
let removedValue = numbers.shift();
console.log(numbers); // [ 2, 3, 4, 5 ]
console.log(removedValue); // 1
You’ll be able to read more about the tutorial array shift in Javascript.
The splice method removes or replaces existing elements with new elements in an array. We can also insert new elements at any specific location in the array.
Syntax of the splice method as follows
splice(start, deleteCount, item1, item2, itemN)
The splice method usually accepts three arguments
The code below inserts the value 4 at index 3. It will remove 0 any elements from the array..
let numbers = [1, 2, 3, 5, 6 ];
// Start 3 Number of elements to delete= 0 items to insert 4
numbers.splice(3,0,4);
console.log(numbers); // [1,2,3,4,5,6]
The following code inserts 9,10 & 11 at index location 3. It also removes the three elements starting from location 3.
let numbers = [1, 2, 3, 5, 6 ];
//start=3 Number of elements to delete= 3 items to insert 9, 10, 11
numbers.splice(3 ,3, 9,10,11);
console.log(numbers); // [ 1, 2, 3, 9, 10, 11 ]
The code below removes the two items from the array starting from index 2.
let numbers = [0, 1, 2, 3, 4, 5];
// it will remove two items starting from the index 2 ( 2 & 3)
numbers.splice(2,2);
console.log(numbers) //[ 0, 1, 4, 5 ]
The copyWithin method is a built-in method that allows us to copy a sequence of elements within an array to another location within the same array, overwriting any existing elements.
copyWithin does not change the length of the array. It copies the elements until the end of the array.length. It will discard anything beyond the array.length.
The syntax for the copyWithin method is as follows.
Array.copyWithin(target, start, end)
Where the target is the index of the element to copy the sequence to, the start is the index of the first element to copy from, and the end is the index of the last element to copy from (but not including).
If any of the argument is a negative integer, the index counts backward from the array’s end.
In this example, we start with an array [1, 2, 3, 4, 5], and we want to copy the sequence of items from index 0 to 1 (2 elements) to index 3 & 4.
Hence, we invoke the copyWithin(3, 0,2).
Here 2 is the target, and 0 is the index of the first element. The 2 is the value of the end argument, which is the following index after the end of the sequence, so we copy two elements in total.
let numArr = [1, 2, 3, 4, 5];
// target=3 start =0 end = 2
// Copies 2 element from index 0 & 1 to index 3 & 4
numArr.copyWithin(3, 0,2);
console.log(numArr);
//output
//[ 1, 2, 3, 1, 2 ]
// Value 1 from index 0 is now copied to index 3
// Value 2 from index 1 is now copied to index 4
// Values at target locations are overwritten
You can refer to the article copyWithin in Javascript
let numbers = [1, 2, 3, 5, 6 ];
//start=3 Number of elements to delete= 3 items to insert 9, 10, 11
numbers.splice(3 ,3, 9,10,11);
console.log(numbers); // [ 1, 2, 3, 9, 10, 11 ]
The code below removes the two items from the array starting from index 2.
let numbers = [0, 1, 2, 3, 4, 5];
// it will remove two items starting from the index 2 ( 2 & 3)
numbers.splice(2,2);
console.log(numbers) //[ 0, 1, 4, 5 ]
The array fill method allows you to set the elements of an array to a specific value.
Syntax of the fill method as follows
fill(value, start, end)
The value parameter is the value that you want to fill the array with.
The start is the starting index from where you’d like to fill the array. It is optional and defaults to index 0.
The endis the ending index up to which you want to fill. It is optional and defaults to the array’s last index (array.length – 1) if omitted.
The start and end can have negative values. In that case, it will count back from the array’s end.
The code below creates a new array from the array constructor function. It will then fills it up with 0 value
const arr = new Array(5);
arr.fill(0);
console.log(arr); // Output: [0, 0, 0, 0, 0]
The code below fills up the portion of the array using fill method.
const arr = [1, 2, 3, 4, 5];
// fill from index 2 to index 4 with value 0
arr.fill(0, 2, 4);
console.log(arr); // Output: [1, 2, 0, 0, 5]
The sort methodaccepts a callback function as an argument and sorts the array using that function. The callback function (known as compareFn) is optional. The sort method will use the default sort if we omit the callback function. The default sorting method converts each element into strings (casts them to strings) and compares their values according to the UTF-16 encoding standard.
The syntax of the sort() method is as follows:
array.sort([compareFn])
The following code sorts the array of numbers. As you can see from the output, 7000 has come before 2000, 21 & 5 because the default sort method converts numbers to strings and then sorts them in ascending order.
const numbers = [1, 300, 7000, 2000, 21, 5];
numbers.sort();
console.log(numbers);
//[ 1, 2000, 21, 300, 5, 7000 ]
To customize the sorting order, we need to provide the compare function. The syntax of which is as follows.
compareFn(a, b)
The compareFn accepts two parameters, a and b, corresponding to the two elements of the array that we are comparing. A positive return value will sort a after b, a negative value will sort b after a, and 0 will keep the original order.
The code below sorts the numbers array in ascending order using the sortNumbers callback function.
const numbers = [1, 300, 7000, 2000, 21, 5];
numbers.sort(sortNumbers);
console.log(numbers);
//[ 1, 5, 21, 300, 2000, 7000]
function sortNumbers(a, b) {
return a - b;
}
instead of separate function, you can make use of arrow function.
const numbers = [1, 300, 7000, 2000, 21, 5 ];
numbers.sort((a,b) => a - b);
console.log(numbers);
//[ 1, 5, 21, 300, 2000, 7000]
You can learn more about how to sort arrays in JavaScript.
The reverse method reverses the order of the elements in an array. It moves first element to last, the second to second last, and so on.
The syntax for the reverse method is as follows:
array.reverse()
The reverse method mutates the original array, meaning it modifies the array in place and returns a reference to the same array with the reversed order of elements.
The following example shows how to use the reverse method on an array.
const arr = [1, 2, 3, 4, 5];
arr.reverse();
console.log(arr); //[ 5, 4, 3, 2, 1 ]
The concat method combines two or more arrays into a new single array and then returns that array. It does not change the original array but returns a new array.
The syntax for the concat() method is as follows:
array.concat(value0, value1, /* … ,*/ valueN)
array is the original array that you want to join with other arrays or values.
The value is the value we want to merge with the original array. It can be an array or just any value. The concat will create a shallow copy of the original array if we omit the values.
The concat will not change the original array. It will always return the new array.
In this example, we create two arrays, numArr1, and numArr2 and then use the concat method to combine them into a new array called numbers.
const numArr1 = [1, 2, 3];
const numArr2 = [4, 5, 6];
const numbers = numArr1.concat(numArr2);
console.log(numbers);
The code below merges two arrays and a few numbers into a new array.
const numArr1 = [1, 2, 3];
const numArr2 = [4, 5, 6];
const numbers = [].concat(numArr1, numArr2, 7, 8, 9 );
console.log(numbers);
//[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
The slice method extracts a portion of an existing array and returns it as a new array.
The syntax of the slice method is as follows.
Array.slice(start, end)
Where start is the starting index, and the end is the ending index of the array section we want to extract.
Slice creates a new array that contains all the elements from the start index up to the end -1 index. Note that it will not copy the element at the end index.
If we omit the start, it will default to 0. If we omit the end, it will default to array.length.
The code below copies the elements from the index 0 to 3 to a new array.
const numArr = [1, 2, 3, 4, 5];
const newArray = numArr.slice(0,3);
console.log(newArray); // [1, 2, 3]
The code below copies everything from the original array to the new array. The numArr.slice() is equivalent to numArr.slice(0,numArr.length);
const numArr = [1, 2, 3, 4, 5];
const newArray = numArr.slice();
//The above code is the same as
//const newArray = numArr.slice(0, numArr.length);
console.log(newArray); // [ 1, 2, 3, 4, 5 ]
The join method joins the elements of an array into a string.
If the array has only one item, it will return it.
If the array has more than one item, it will concatenate each element separated by a separator and returns it.
We can specify the separator as the first argument.
It will treat undefined, null, and empty slots as empty strings.
Syntax
array.join(separator)
Where the separator is the separator that you wish to use, if omitted, it will use the comma.
The following example creates an array of fruits. It shows how you can use the join statement to convert them into a string.
const fruits = ['Apple', 'Oranage', 'Banana'];
console.log(fruits.join());
//Apple,Oranage,Banana
console.log(fruits.join(''));
// AppleOranageBanana
console.log(fruits.join('-'));
// Apple-Oranage-Banana
The flat method lets us flatten a nested array into an array of single dimensions.
The syntax for using the flat is as follows.
array.flat([depth])
Where array is the array we want to flatten.
The depth is an optional argument that specifies the maximum nesting depth to flatten.
For example, if we set the depth as 2, the flat will flatten nested arrays until depth 2. nested arrays beyond depth 2 will return unchanged.
If we omit the depth, it will default to 1.
If the depth is 0, the flat method will return the original array unchanged.
In the code below, the nestedArray is an array with depth 2.
//Array nested upto depth 2
const nestedArray = [1, [2, 3], [[4], [5, 6]]];
//More examples
//depth 1 (default)
flattenedArray = nestedArray.flat();
console.log(flattenedArray); // [ 1, 2, 3, [ 4 ], [ 5, 6 ] ]
//depth 1. Same as above
flattenedArray = nestedArray.flat(1);
console.log(flattenedArray); // [ 1, 2, 3, [ 4 ], [ 5, 6 ] ]
//depth 0. retuns unchanged
flattenedArray = nestedArray.flat(0);
console.log(flattenedArray); // [ 1, [ 2, 3 ], [ [ 4 ], [ 5, 6 ] ] ]
//depth 2. Flattens upto depth 2
flattenedArray = nestedArray.flat(2);
console.log(flattenedArray); // [ 1, 2, 3, 4, 5, 6 ]
//-ve depth same as depth 0
flattenedArray = nestedArray.flat(-1);
console.log(flattenedArray); // [ 1, [ 2, 3 ], [ [ 4 ], [ 5, 6 ] ] ]
The flatMap method transforms the original array using a map function and then flattens it to the depth of 1.
The flatMap iterates over an array, execute a provided map function once for every array element, and uses the result to create a new array. It then flattens the array to a depth of 1.
It is similar to the calling map method followed by the flat method with a depth of 1. But it is slightly more efficient than calling those two methods separately.
The syntax of flatMap is as follows:
flatMap(callbackFn, thisArg)
The element parameter is the current element being processed, the index parameter is the current element’s index, and the array parameter is the array being processed.
thisArg – An optional parameter that specifies the value to be used as this when executing the callback function.
The flat method lets us flatten a nested array into an array of single dimensions.
The code below contains array of numbers. The callback function multiplies each element by 2 and returns the array, which is then flattened
const arr = [1, 2, 3, 4];
const flattened =arr.flatMap((x) => [x * 2]);
console.log(flattened)
// [2, 4, 6, 8]
The indexOf method searches for a given element within a given array. It starts searching for the items from index 0 and returns the index of the first occurrence of the given element in the array. If the element does not exist, then it will return -1.
The syntax of the indexOf method is as follows:
indexOf(element, startIndex)
Where element is the element to be searched in the array, and startIndex is the optional index from which to start the search.
If the startIndex is negative, the search will start from the startIndex + array.length. i.e., it will count back from the end of the array
const arr = [1, 2, 3, 4, 5, 6];
//Search for 2
console.log(arr.indexOf(3)); //2
//Start search from index 2
console.log(arr.indexOf(3,2)); //2
//Start search from index 4
console.log(arr.indexOf(3,4)); //-1
//Start search from index 2 (becuase 6-4=2)
console.log(arr.indexOf(3,-4)); //2
The lastIndexOf method searches for a given element within a given array. It starts searching for the item from the last index of the array and searches backward. Hence it returns the index of the last occurrence of the given element. If the element does not exist, then it will return -1.
The syntax of the lastIndex is as follows
lastIndexOf(element, fromIndex)
The element is the element to be searched in the array, and fromIndex is the optional index from which to start the search. Note that the search will begin from fromIndex and searches backwards until the index 0.
If the fromIndex is negative, the search will start from the fromIndex + array.length. i.e., it will count back from the end of the array
const fruits = ['apple', 'banana', 'orange', 'apple', 'pear'];
//start search from index array.length-1 i.e.4
lastIndex = fruits.lastIndexOf('apple');
console.log(lastIndex); //3
//start search from index 2. Hence returns 0
lastIndex = fruits.lastIndexOf('apple',2);
console.log(lastIndex); //0
The find method searches elements in the array using search criteria and checks if any element satisfies that criterion. If a match is found, it returns the first element that matches the criteria. Else returns undefined.
The syntax of the find method is as follows.
find(callbackFn, thisArg)
Where callbackFn is a function that find method invokes for each element of the array. It will contain the logic to check elements of the array. The callbackFn takes up to three arguments (element, index, array) and must return true if the element matches the search criteria.
In the code below, we have an array of fruits. We are using the find() method to search for the element ‘mango’. The findLogic is the callback function, which returns true if the value of the element is mango and else false.
const fruits = ['apple', 'banana', 'mango', 'orange', 'papaya'];
const result = fruits.find(findLogic);
console.log(result); //mango
function findLogic(element) {
if (element==='mango') return true
return false
}
You can also use an arrow function.
const fruits = ['apple', 'banana', 'mango', 'orange', 'papaya'];
const result = fruits.find(fruit => fruit === 'mango');
console.log(result); //mango
The findIndex method searches elements in the array using search criteria and checks if any element satisfies that criterion. If a match is found, it returns the index of the first element that matches the criteria. Else returns -1.
The findIndex is the same as the find method. The only difference is that the find returns the value of the element while findIndex returns its index.
The syntax of the findIndex is as follows.
findIndex(callbackFn, thisArg)
Example of findIndex
const fruits = ['apple', 'banana', 'mango', 'orange', 'papaya'];
const result = fruits.findIndex(fruit => fruit === 'mango');
console.log(result); //2
The findLast method searches elements in the array in reverse order using search criteria and checks if any element satisfies that criterion. If a match is found, it returns the first element that matches the criteria. Else returns undefined.
findLast is similar to the find method. The find method searches from the beginning of the array, and the findLast searches from the end of the array.
The syntax of the findLast method is as follows.
findLast(callbackFn, thisArg)
The following is an example of the findLast method.
const fruits = ['apple', 'banana', 'mango', 'orange', 'papaya'];
const result = fruits.findLast(fruit => fruit === 'mango');
console.log(result); //mango
The findLastIndex is similar to the findLast method. It searches elements in the array in reverse order using search criteria and checks if any element satisfies that criterion. If a match is found, it returns the index of the element that matches the criteria. Else returns -1
findLast is similar to the find method. The find method searches from the beginning of the array, and the findLast searches from the end of the array.
The syntax of the findLast method is as follows.
findLast(callbackFn, thisArg)
The following is an example of the findLast method.
const fruits = ['apple', 'banana', 'mango', 'orange', 'papaya'];
const result = fruits.findLast(fruit => fruit === 'mango');
console.log(result); //mango
The forEach method iterates over an array and executes a provided function once for every array element.
forEach method can be used as an alternative to looping statements like for, for…of, and for…in.
The syntax of forEach is as follows.
forEach(callbackFn, thisArg)
callbackFn- A function that forEach method invokes for each element of the array. The callbackFn takes up to three arguments (element, index, array). The syntax is as follows.
callbackFn(element, index, array)
The element parameter is the current element being processed, the index parameter is the current element’s index, and the array parameter is the array being processed.
In this code, we declare an anonymous callback function that simply logs each element to the console.
let myArray = [1, 2, 3, 4, 5];
myArray.forEach(function(element) {
console.log(element);
});
//1 2 3 4 5
The entries method allows us to create an iterator object from an array containing each index’s key/value pairs.
Each key-value pair the entries method returns is an array with two elements. The first element is the index number, and the second is its corresponding value.
The syntax of the entries method is as follows.
entries()
The code below uses the for of loop to iterate over iterated returned by the entries method. The element in the array is “a” and its index position is 0. Hence the iterator returns [ 0, ‘a’ ]
const a = ["a", "b", "c"];
for (const e of a.entries()) {
console.log(e);
}
//[ 0, 'a' ]
//[ 1, 'b' ]
//[ 2, 'c' ]
The element parameter is the current element being processed, the index parameter is the current element’s index, and the array parameter is the array being processed.
In this code, we declare an anonymous callback function that simply logs each element to the console.
let myArray = [1, 2, 3, 4, 5];
myArray.forEach(function(element) {
console.log(element);
});
//1 2 3 4 5
The values method allows us to create an iterator object from an array containing the values of each element in an array in the order they appear.
It is similar to entries method, but only returns the values. The keys method returns the only keys.
The syntax of the values method is as follows
values()
Example
const a = ["a", "b", "c"];
for (const e of a.values()) {
console.log(e);
}
//a
//b
//c
The Keys method allows us to create an iterator object from an array containing the keys of each element in an array in the order they appear.
It is similar to entries method, but only returns only the keys. It is also similar to values method, which only returns values.
The syntax of the values method is as follows
keys()
Example
const a = ["a", "b", "c"];
for (const e of a.keys()) {
console.log(e);
}
//0
//1
//2
The array map method allows us to create a new array by transforming each element of an existing array using a callback function. It iterates over each element of an array, invokes the callback function, and uses the result to create a new array.
The Syntax of the map method is as follows.
array.map(callbackFn , thisArg)
The callbackFn is the callback function invoked against each element of the existing array.
thisArg is an optional value that becomes the this of executing the callback function.
The Syntax of the callbackFn is as follows.
callbackFn(currentValue, index, array)
Where the currentValue is the current element being processed by the map method. Index (optional) is the current element’s index, and array (optional) is the array being processed.
The code below creates a new array doubledNumbers by multiplying each element of the existing array by two.
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(num => num * 2);
console.log(doubledNumbers);
Array filter allows us to create a new array by filtering out the elements of a given array. It does that by using a filter function. The filter method iterates over every array element and executes the filter function. It will create a new array with all elements that pass the filter function.
The Syntax of the Javascript filter method is as follows.
array.filter(filterFn, thisArg)
The filterFn is the callback function invoked against each element of the existing array. It must return true or false.
thisArg is an optional value that becomes the this of executing the filterFn function.
The Syntax of the callbackFn is as follows.
filterFn(currentValue, index, array)
The currentValue is the current element of the array being processed by the filter method. Index (optional) is the current element’s index, and array (optional) is the array.
The filter method in the following example takes in a number and returns true if the number is odd. The filter method then returns a new array containing only the odd numbers.
const numArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12];
const oddNumArr = numArr.filter((num) => num % 2 !== 0);
console.log(oddNumArr); // [1, 3, 5, 7, 9, 11]
The reduce method reduces the array to a single value. It iterates over each element of the array and invokes a callback function. The callback function (the reducer function) returns a single output value.
The syntax of the reduce method is as follows.
reduce(reducerFn, initialValue)
The reducer function (reducerFn) takes four arguments. The first two arguments are the accumulator and the current value of the array. It returns the updated value of the accumulator, which it will use as the accumulator for the next iteration.
An initialValue is optional and is the initial value of the accumulator. If no value is specified, it will use the first element of the array as the initial value.
The syntax of the reducer function is as follows.
function (accumulator, currentValue, currentIndex, array)
The code below uses the reduce method to calculate the sum of all the elements of a numbers array.
const numArr = [1, 2, 3, 4, 5];
sum = numArr.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
});
console.log(sum); // Output: 15
//with initial value
sum = numArr.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
},10);
console.log(sum); // Output: 25
The reduceRight method reduces the array to a single value. It iterates over each array element in descending-index order and invokes a callback function. The callback function (the reducer function) returns a single output value.
The reduceRight is similar to the reduce method. The only difference is that it iterates array in descending order
const numArr = [1, 2, 3, 4, 5];
sum = numArr.reduceRight((accumulator, currentValue) => {
return accumulator + currentValue;
});
console.log(sum); // Output: 15
//with initial value
sum = numArr.reduceRight((accumulator, currentValue) => {
return accumulator + currentValue;
},10);
console.log(sum); // Output: 25
Every method tests to see if all elements in an array pass a particular test. It invokes the callback function on every element of the array. If callback returns true for every element, then the method will return true else, false
The syntax of every method is as follows:
every(callbackFn, thisArg)
callbackFn is the callback function that the Every method will invoke against each array element.
ThisArg is an optional parameter specifying the value to be used for this when executing the callback function.
The syntax of the callbackFn is as follows:
callbackFn(element, index, array)
Where
Element is the current element being processed in the array.
Index (optional) is the index of the current element being processed.
Array (optional) is the array that every() was called upon.
const numArr = [1, 2, 3, 4, 5];
result = numArr.every((e) => {
return e > 0;
});
console.log(result); //true
const numArr = [1, 2, 3, 4, 5];
result = numArr.every((e) => {
return e > 3;
});
console.log(result); //false
Some method tests to see if at least one element in an array pass a particular test. It invokes the callbackFn function on every element of the array. If callBackFn returns true for any one of the element, then the method will return true else, false.
The syntax of every method is as follows:
some(callbackFn, thisArg)
The syntax is similar to every method
const numArr = [1, 2, 3, 4, 5];
result = numArr.some((e) => {
return e > 3;
});
console.log(result); //true
result = numArr.some((e) => {
return e > 5;
});
console.log(result); //false
The array length property of the JavaScript array returns the number of elements the array can hold. The length also includes the number of elements plus empty slots (in the case of sparse arrays), if any, in that array. We can also use the length property to increase or shorten the array’s length
//Example
const books = ["Ulysses", "Don Quixote", "War and Peace", "Moby Dick"];
console.log(books.length) //4