JavaScript Arrays
About JavaScript Array
In JavaScript, an array is used to store multiple data values in a single variable.
Arrays are versatile and powerful data structure for handling collections of data. They can be considered as an ordered list of items.
Arrays can hold elements of various data types, such as numbers, strings, objects, and even other arrays.
Array's values (elements) can be accessed using a numeric index starting from 0.
Creating an Array
JavaScript array can be created primarily in two ways- array literal and array constructor:
Array Literal:
An array can be created using square brackets '[]'. The values are placed within the square brackets '[]' separated each value by comma ',' as demonstrated in the following example:
Example of Creating Array Using Array Literal Syntax
Explanation of the code
-
let fruitsArr = ["apple", "banana", "cherry"];: This line declares an array named 'fruitsArr' initializing the array with values "apple", "banana", "cherry". Values are placed within the square brackets and separated each value by comma. -
console.log(fruitsArr);: This line of code prints the array in the console.
Array Constructor:
An array can be created by using the Array constructor 'new Array()' as demonstrated in the following example:
Example of Creating Array Using Array Constructor
Explanation of the code
-
let fruitsArr = new Array("apple", "banana", "cherry");: This line declares an array named 'fruitsArr' using 'new Array()'. Array values "apple", "banana", "cherry" are placed within the parentheses of the constructor and separated each value by comma. -
console.log(fruitsArr);: This line of code prints the array in the console.
Empty Array Using Array Constructor:
An empty array can be created by using the Array constructor 'new Array()' and element (value) can be added later as demonstrated in the following example:
Example of Creating Empty Array Using Array Constructor
Explanation of the code
-
let fruitsArr = new Array();: This line declares an empty array using Array Constructor. -
fruitsArr[0] = ("Apple");: This line add a value to the 'fruitsArr' array at 0 index. -
console.log(fruitsArr);: This line of code prints the array in the console.
Accessing Array Elements
Array elements can be accessed using index of the element. Array index starts from 0. Index is placed within square brackets '[]' after the array variable name.
Example of Accessing Array Elements
Output of the above example
apple
orange
Explanation of the code
-
let fruitsArr = new Array("apple", "banana", "orange");: This line declares an array with 3 elements. -
console.log(fruitsArr[0]);: This line of code prints the first element of the array in the console. Here,fruitsArr[0]refers to the first element as index 0 refers to the first element. -
console.log(fruitsArr[2]);: This line of code prints the third element of the array in the console. Here,fruitsArr[2]refers to the third element as index 2 refers to the third element.
Modifying & Adding Array Elements
Modifying Array Elements
Array elements can be modified assigning new value to the existing element. Element needs to be specified with element index within square brackets '[]' after the array variable name.
Example of Modifying Array Elements
Explanation of the code
-
let fruitsArr = new Array("apple", "banana", "orange");: This line declares an array with 3 elements. -
fruitsArr[2] = "cherry";: This line modifies the value of third element of the array by assigning new value "cherry" to thefruitsArr[2].
Adding Array Elements
Elements can be added to an existing array using "push" method or using a new index of the array.
Example of Adding Array Elements
Explanation of the code
-
et fruitsArr = new Array("apple");: This line declares an array with 1 element. -
fruitsArr[1] = "banana";: This line adds an element to the 'fruitsArr' array by assigning new value "banana" to the new indexfruitsArr[1]. -
fruitsArr.push("orange");: This line adds another element (value "orange") to the 'fruitsArr' array by using 'push' method.
Length Property of Array
Length property of array is used to get the length of the array i.e. number of the elements in the array.
Example of Array Length Property
Output of the above example
The length of the array is 5
Explanation of the code
-
var len = numsArr.length;: In this line of code,numsArris the array andlengthis the length property of the array. It returns the number of elements of the 'numsArr' array and passes the returned value to 'len' variable.
Iterating (looping) Through Array Elements
JavaScript arrays are iterable as they implement the iterable protocol.
Using 'for' Loop
You can iterate over an array using 'for' loop.
Example of Using 'for' Loop
Output of the above example
apple
banana
orange
Using 'for...of' Loop
You can iterate over the values of an array using 'for...of' loop.
Example of Using 'for...of' Loop With Array
Output of the above example
apple
banana
orange
Using 'for...in' Loop
You can iterate over the indexes of an array using 'for...in' loop.
Example of Using 'for...in' Loop with Array
Output of the above example
0
1
2
apple
banana
orange
Methods of Array (Advanced Level)
1. push():
The push() method adds one or more elements to the end of an array.
Example of push() Method
2. pop():
The pop() method removes (deletes) the last element from an array.
Example of pop() Method
3. unshift():
The unshift() method adds one or more elements to the beginning of an array.
Example of unshift() Method
4. shift():
The shift() method removes the first element from an array.
Example of shift() Method
5. splice():
The splice() method is used to add or remove element at a specific index. The splice() method also returns an array containing the removed elements.
Example of Adding Element Using Splice() Method
Explanation of the code
-
fruitsArr.splice(2, 0, "orange");: In this line of code, the splice() method takes 3 arguments. The first argument2refers the starting index at which the changing of the array will start and the second argument0refers to the number of elements to remove from the array(No element will be removed as the number is '0'.). The third argument"orange"is the element to be added to the array.
Example of Removing Elements Using Splice() Method
Explanation of the code
-
fruitsArr.splice(2, 2);: In this line of code, the splice() method takes 2 arguments. The first argument2refers the starting index at which the changing of the array will start and the second argument2refers to the number of elements to be removed from the array. The two elements of the array"mango", "orange"will be removed as the number is '2'.
6. slice():
The slice() method is used to return a new array slicing elements from the source array.
Example of Slice() Method
Explanation of the code
-
let newArray = fruitsArr.slice(2, 4);: In this line of code, the slice() method takes 2 arguments. The first argument2is the starting index at which the selection will start and the second argument4refers to the index upto which the selection will continue (The index 4 is not inclusive).
7. concat():
The concat() method is used to combine two or more arrays.
Example of concat() Method
8. indexOf():
The indexOf() method returns the index of first occurrence of the specified element.
Example of indexOf() Method
9. includes():
The includes() method checks whether an array includes the specified element and returns Boolean value 'true' or 'false'.
Example of includes() Method
10. reverse():
The reverse() method reverses the order of elements in an array.
Example of reverse() Method
11. join():
The join() method returns a new string by concatenating (joining) all the elements of the array, separated by the specified separator. The separator is an optional argument of the method.
Example of join() Method
12. split():
The split() method is a string method that splits a string into an array of substrings based on a specified delimiter or separator and returns an array.
Example of split() Method
13. sort():
The sort() method sorts the elements of an array in lexicographical order (alphabetical order) by default. The method can be customized.
Example of sort() Method
Example of Sorting Number Elements in Ascending & Descending Order
Example of Sorting String Elements in Descending Order
14. filter():
The filter() method is used to create a new array with elements that pass a specific test (set by the callback function on each element).
Example of filter() Method
15. map():
The map() method is used to create a new array with the results of calling a function on every element.
Example of map() Method
16. reduce():
The reduce() method is used to reduce an array to a single value.
Example of reduce() Method
17. every():
The every() method is used to check if all elements pass a test and it returns a Boolean value.
Example of every() Method
18. some():
The some() method is used to check if at least one element passes a test and it returns a Boolean value.
Example of some() Method
19. find():
The find() method returns the first element that satisfies a test.
Example of find() Method
20. findIndex():
The findIndex() method returns the index of the first element that satisfies a test.
Example of findIndex() Method
21. flat():
The flat() method flattens nested arrays into a single array.
Example of flat() Method
22. flatMap():
The flatMap() method maps and flattens the array in one step. The method first maps all elements of an array and then it flattens the array and returns it.
Example of flatMap() Method
Break Down of the Above Example
In the above example, the array was first mapped using map() method, then it was flattened by flat() method. These two tasks can be done with a single flatMap() method.
23. toString():
The toString() method converts an array into a comma-separated string of its elements.
Example of toString() Method
JavaScript Compiler For Live Practice
Practice the above JavaScript code in the following JavaScript Compiler. Create more JavaScript arrays and experiment with different array methods in the following editor and click Execute button to check the output. The output will be displayed in JavaScript Code Output section.
JavaScript Compiler