In JavaScript, array is a single variable that is used to store different elements. It is often used when we want to store a list of elements and access them by a single variable. Unlike most languages where array is a reference to the multiple variables, in JavaScript array is a single variable that stores multiple elements.
There are 3 ways to construct array in JavaScript
By array literal
By creating instance of Array directly (using new keyword)
By using an Array constructor (using new keyword)
Detailed Explanation
1.JavaScript array literal
var array name=[value1,value2.....valueN];
As you can see, values are contained inside [] and separated by, (comma).
Let's see the example of creating and using array in JavaScript.
<script>
var emp=["Piyush","Hitesh","Anurag"];
for (i=0;i<emp.length;i++){
document. Write(emp[i] + "<br/>");
}
</script>
Remarks-The .length property returns the length of an array.
Output of the above Example
Piyush
Hitesh
Anurag
2.JavaScript Array directly (new keyword)
Syntax
var arrayname=new Array();
Here, new keyword is used to create instance of array.
Let's see the example of creating array directly
<script>
var i;
var emp = new Array();
emp[0] = "Piyush";
emp[1] = "Hitesh";
emp[2] = "Anurag";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Output of the above example
Piyush
Hitesh
Anurag
3.JavaScript array constructor (new keyword)
Here, you need to create instance of array by passing arguments in constructor so that we don't have to provide value explicitly.
An example of creating an object by array constructor is given below.
<script>
var emp=new Array("Piyush","Hitesh","Anurag");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Output of the above example
Piyush
Hitesh
Anurag
JavaScript Basic Array Methods
Array.push() : Adding Element at the end of an Array. As array in JavaScript are mutable object, we can easily add or remove elements from the Array. And it dynamically changes as we modify the elements from the array.
Syntax
Array.push(item1, item2 …) Parameters: Items to be added to an array.
Array.unshift() :Adding elements at the front of an Array
Syntax
Array.unshift(item1, item2 …)
Parameters: Items to be added to the array
3.Array.pop() :Removing elements from the end of an array
Syntax
Array.pop()
Parameters: It takes no parameter
4. Array.shift():Removing elements at the beginning of an array
Syntax
Array.shift()
Parameter : it takes no parameter
5. Array.splice() : Insertion and Removal in between an Array
syntax
Array.splice (start, deleteCount, item 1, item 2….)
Parameters:
Start : Location at which to perform operation
deleteCount: Number of element to be deleted,
if no element is to be deleted pass 0.
Item1, item2 …..- this is an optional parameter .
These are the elements to be inserted from location start
JavaScript Array sort() Method
let's understand by program
<script>
// JavaScript to illustrate sort() function
function func() {
// Original string
var arr = ["Piyush", "Mani", "Chaubey"]
document. Write(arr);
document. Write("<br>");
// Sorting the array
document. Write(arr.sort());
}
func();
</script>
Desired output
Piyush,Mani,Chaubey
Chaubey,Piyush,Mani
The arr.sort() method is used to sort the array in place in a given order according to the compare() function. If the method is omitted then the array is sorted in ascending order.
Syntax:
arr.sort(compareFunction)
JavaScript | Array Iteration Methods
Array iteration methods perform some operation on each element of array. There are some different examples of Array iteration methods are given below.
Array.forEach() function: The array.forEach() function calls the provided function(a callback function) once for each element of the array. The provided function is user defined, it can perform any kind of operation on array
Syntax
array.forEach(function callback(value, index, array){ }[ThisArgument]);
Parameters: This function accepts three parameters as mentioned above and described below:
value: This is the current value being processed by the function: index: Item index is the index of the current element which was being processed by the function: array: The array on which the .forEach() function was called:
How to select a random element from array in JavaScript ?
Approach 1:
Use Math.random() function to get the random number between(0-1, 1 exclusive).
Multiply it by the array length to get the numbers between(0-arrayLength).
Use Math.floor() to get the index ranging from(0 to arrayLength-1).
Approach2
The random(a, b) method is used to generates a number between(a to b, b exclusive)
Taking the floor value to range the numbers from (1 to arrayLength)
Subtract 1 to get the index ranging from(0 to arrayLength-1).
Check if an array is empty or not in JavaScript
Method 1: Using Array.isArray() method and array. Length property: The array can be check if it is actually an array and it exists by the Array.isArray() method. This method returns true if the Object passed as a parameter is an array. It also checks for the case if the array is undefined or null.
The array can be checked if it is empty by using the array.length property. This property returns the number of elements in the array. If the number is greater than 0, it evaluates to true. This method and property can be both used together with the AND(&&) operator to determine whether the array exists and is not empty.
Syntax
Array.isArray(emptyArray) && emptyArray.length