Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

Array Methods in Java Script

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.

Array Methods

Following are all the methods available on arrays in JavaScript

Check if it is an Array

IsArray

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.

Example

                            
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
 
                            
                        
                            
                        

Create Array

from

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

  1. indexed elements (i.e., the object has sequential access to its properties);
  2. has a length property.

For Example, the arrLike object below looks like an array with integer property names and a length property

Example

                            
const arrLike = { 0: 'foo', 1: 'boo', 2: 'koo', length: 3 };
 
console.log(arrLike[0])    //foo
console.log(arrLike.length)    //3
 
                            
                        
                            
                        

We can easily convert array-like objects using the from method.

Example

                            
const arrLike = { 0: 'foo', 1: 'boo', 2: 'koo', length: 3 };
 
console.log(Array.isArray(arrLike))  //false
 
let arr = Array.from(arrLike)
 
console.log(Array.isArray(arr))  //true
console.log(arr)  //[ 'foo', 'boo', 'koo' ]
 
                            
                        
                            
                        

You can read more from the tutorial array from in Javascript.

of

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]
                            
                        
                            
                        

Read Values

at

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)
                            
                        
                            
                        

Add/Remove/Modify elements

push

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

pop

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

unshift

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 ]
 

                    

                    

shift

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.

splice

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

  1. The start is the index of the array where we start changing the array.
  2. deleteCount is the number of items to be removed from the start index
  3. item1, item2, itemN, etc., are the elements to add to the array at the index start

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 ]
 
 
 

                    

                    

CopyWithin

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 ]
 
 
 

                    

                    

fill

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]
 
 
 

                    

                    

Sorting Arrays

sort

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.

reverse

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 ]


    
                    
    
                        

Merge & Split Arrays

concat

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 ]
 
 
                            
                        
                            
                        

Slice

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 ]


    
                        
    
                    

Flatten Array

Join

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

                                

                                

flat

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 ] ] ]



                                    

                                

flatMap

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]

                                

                                

Loop

forEach

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 
 
 
                            
                        
                            
                        

entries

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 
 
 
                            
                        
                            
                        

Values

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
  
 
        
        

keys

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
  
 
        
        

Transform an Array

map

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);
 
                            
                               
                        

Filter

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]
                               
                        

Misc

reduce

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
       

reduceRight

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

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

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
  
        
    

Array Properties

Length

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
 
                            
                         

Array length property in JavaScript