What is an Array in JavaScript?
An array in JavaScript is an object that contains similar or different types of items. Those items can be variables (numbers or strings) or even other objects as well.
How to Create a JavaScript Array
Method 1
A new instance of a JavaScript array object can be created in the same way as any other object is created in JavaScript using the new keyword.
Array Declaration
/*Array Declaration*/
var myArray=new Array();
Array Initialization
/*Array Initialization*/
myArray[0] = "Red";
myArray[1] = "Green";
myArray[2] = "Indigo";
myArray[3] = "Violet";
Method 2
We can also initialize the array during the array declaration with the help of an array literal.
var myArray=["Red","Green","Indigo","Violet"];
JavaScript Array Methods
1. concat() :-
The concat() method combines two or more arrays and returns a new Array. This concat() method doesn't make any change in the original array.
Example-
let arr1=[2,4,6,8];
let arr2=[3,5,7,9];
let result=arr1.concat(arr2);
console.log(result);
Output-
[2,4,6,8,3,5,7,9]
2. indexOf()
The indexOf method returns the first position at which a given element appears in an array.
Exapmle-
let arr1=[2,4,6,8];
console.log(arr1.indexOf(6));
Output-
2
3. pop()
The pop() method removes the last element of an array.
Example-
let arr1=[2,4,6,8];
arr1.pop();
console.log(arr1);
Output-
[2,4,6]
4. push()
The push() method adds a new element at the end of an array.
Example-
let arr1=[2,4,6,8];
arr1.push(9);
console.log(arr1);
Output-
[2,4,6,8,9]
5. reverse()
The resverse() method reverse the order of the elements in an array.
Example
let arr1=[2,4,6,8];
arr1.reverse();
console.log(arr1);
Output-
[8,6,4,2]
6.shift()
The shift() method removes the first element of an array.
Example
let arr1=[2,4,6,8];
arr1.shift();
console.log(arr1);
Output
[4,6,8]
7. unshift()
The unshift() method adds a new element to the beginning of an array.
Example-
let arr1=[2,4,6,8];
arr1.unshift(3);
console.log(arr1);
Output-
[3,2,4,6,8]
8. slice()
The slice() method pulls a copy of a portion of an array into a new array.
Example-
let arr1=[2,4,6,8,13,15];
console.log(arr1.slice(2,5));
Output-
[6,8,13]
9.splice()
The splice() method lets you modify an array in-place by adding and removing elements. It is most commonly used to remove elements from an array, but it can also be used to add elements to the middle of an array.
Example(At position 2, add 2 elements)
/*At position 2, add 2 elements*/
let myarray=["One", "four", "Six", "Eight"];
myarray.splice(2,0,"two","three");
console.log(myarray);
Output
['One', 'four', 'two', 'three', 'Six', 'four']
Example(At position 2, remove 2 items)
/*At position 2, remove 2 items*/
let myarray=["One", "four", "Six", "Eight"];
myarray.splice(2,2, "two", "three");
Output-
['One', 'four', 'two', 'three']