DEV Community

Niranjan200321
Niranjan200321

Posted on

Array in Javascript

What is array in Javascript?

In other programming languages array is collection of similar data type , But in javascript array is defined collection of elements .Also array is used to store elements.

Example
let arr=[5,44,6,3]
arr[0]=5
arr[1]=44
arr[2]=6
arr[3]=3

Array Methods

_In basically there have lot of methods in array _

Push()

This method is used to insert the value into the array as a last value
Example
let animals=["cat","dog","rabbit","cow"]
push("Jackle");
colsole.log(animals); //["cat","dog","rabbit","cow","jackal"]

pop()

This method is used to remove the last value of an array
Example
let animals=["cat","dog","rabbit","cow","jackal"]
pop();
conlose.log(animals) //["cat","dog","rabbit","cow"]

unshift()

The unshift () is used to add first value into an array
Example
let animals=["cat","dog","rabbit","cow","jackal"]
unshift("Lion");
console.log(animals);//["Lion" ,"cat","dog","rabbit","cow","jackal"]

shift()

The shift() is used to remove the first value of an array .
Example
let animals=["Lion" ,"cat","dog","rabbit","cow","jackal"]
shift();
console.log(animals) //["cat","dog","rabbit","cow","jackal"]

splice()

The splice () is used to delete any number of values and add any number of values in array.
There have 3 parts of values in splice method
splice(starting index , Delete number of index, inserting index)
Example
let animals=["Lion" ,"cat","dog","rabbit","cow","jackal"]
splice(0 1 "Tiger")
The first 0 is defined to the index number of the array , Second 1 is defined to how many elements you waant to remove from array and the third element is defined to replace the remove elements.
_Here the 0 index is Lion in 0 index one element will be delete and the delete element is lion if I will write 2 then in 0 index there 2 elements will be delete and after delete the element the new element will replace which I have defined after delete elements number _
console.log(animals) // ["Tiger" ,"cat","dog","rabbit","cow","jackal"]

Top comments (0)