what is Array?
An array is a particular variable, which can hold more than one value:
const fruits = ["Apple", "Banana", "Orange"];
why Array?
As Array can store n number of values, it is easy to store and access data.
for example:- suppose we have to store the data of fruits, so to do that we have two options.
option 1:- create the n number of variable for n number of fruits
let fruit1 = "Apple"; let fruit2 = "Banana"; let fruit3 = "Orange";
option 2:- create an array and store n number of fruits in it.
const fruits = ["Apple", "Banana", "Orange"];
creating an array
const fruits = ["Apple", "Banana", "Orange"];
another way using the keyword
new
const fruits = new Array("Apple", "Banana", "Orange");
accessing an element of the array
to access the array element you can use its index number
, by default the index number
starts with 0
const fruits = ["Apple", "Banana", "Orange"];
let fruit = fruits[0];
changing the element of the array
fruits[0] = "PineApple";
another way
const fruits = ["Apple", "Banana", "Orange"]; fruits[0] = "PineApple";
access all elements of the array
const fruits = ["Apple", "Banana", "Orange"];
document.getElementById("demo").innerHTML = fruits;
Array Methods
.length
.pop()
the
pop
method is used to remove the last element of the array.push()
push()
method is used to add the element at the end of the array.concat
.concat
is used to combine the values of two array.indexOf()
.indexOf
is used to find theindex number
of the given element of the array.lastIndexOf()
lastIndexOf()
is used to find the last time the item was repeated.join()
.reverse()
.reverse()
method is used to position the elements of the array in reverse order.sort()
.toString()
.copyWithin()