JavaScript Arrays

What is Array ?
Array is like a container that stores one or more values of different data types like number, string etc.
Array Index in javascript starts with 0 and we can access array items using this index number.
Array Syntax
- In JS, arrays are defined using '[ ]' square brackets.
let superHeros=["Ironman","Captain America","Hulk","Thor"];
let count=[1,2,3,4];
let mix=[1,"Apple","Ironman"];
- Access array items using index.
superHeros[2]; //output: "Captain America"
Array methods & properties
Array Length
- Use length Property to get the length of array.
console.log("array length is:", array.length); //output: length value
Pushing elements to array
- use push( ) method to push items into array. Push method pushes item to the end of array.
Syntax: array.push(stringName)
console.log(superHeros.push("Black Panther")); //returns new length of array
Popping elements from array
- Use pop( ) method to pop the last item from array.
console.log(superHeros.pop()); //returns popped out value
Finding index of elements in array
Find index of any element using indexOf() method. If the element is not present method returns -1.
console.log("Index of captain is ",superHeros.indexOf("Captain America"));
//output: Index of captain is 1
Slicing the array
Slice() method can be used to slice the array into sub-array. This method returns a copy/new array and doesn't modify original array.
Syntax: array.slice[start:end]
End index is ignored and array is sliced till 'end-1' index.
console.log("sliced array from 1:3: ",superHeros.slice(1,3));
//output: sliced array from 1:3: [ 'Captain America', 'Hulk' ]
Splicing the array
Splice() method removes elements from an array and, if we pass new values, inserts new elements in their place. This method returns the deleted elements.
Syntax: Splice(start position, delete count,element1,element2...)
console.log(superHeros.splice(1,2,"Ant-man")); // [ 'Captain America', 'Hulk' ]
console.log("spliced array ",superHeros);
//output: spliced array [Ironman","Ant-man","Thor"]
Concat arrays
concat() method is used to concat two or more arrays without modifying existing arrays
let array1=[1,2,3,4];
let array2=[5,6,7,8];
let array3=[];
console.log("concated array ",array3.concat(array1,array2));
//[ 1, 2, 3, 4,5, 6, 7, 8]



