What is ARRAY?
In JavaScript, array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable.
Array declaration
We can declare an array in two ways
1- const array_name = [item1, item2,...];
2- const array_name = new Array(item1, item2,..);
Methods inside an Array
Length
It gives the number of element inside the array.
const count = ["India", "Norway", "China"];
console.log(count);
Output:
3
Slice
It removes a section from an array and creates a new array. But, it doesn't modifies the original array.
const count = ["one", "two", "three", "four"];
const removed = count.slice(1, 3);
console.log(removed);
console.log(count)
Output:
["two", "three"]
["one", "two", "three", "four"]
Splice
It can add and remove some new items in array.and It will modify the original array.
const count = ["one", "two", "three", "four"];
const removed = count.splice(0, 2);
console.log(removed);
console.log(count);
Output:
["one", "two"]
["three", "four"]
Push
It is used to add extra items inside an array at the end.
const count = ["one", "two", "three", "four"];
count.push("five");
console.log(count);
Output:
["one", "two", "three", "four", "five"]
Pop
It is used to remove items from the end of an array.
const count = ["one", "two", "three", "four"];
count.pop();
console.log(count);
Output:
["one", "two", "three"]
Unshift
It is used to add items at the starting of an array.
const count = ["one", "two", "three", "four"];
count.unshift("zero");
console.log(count);
Output:
["zero", "one", "two", "three", "four"]
Shift
It is used to remove items from the start of an array.
const count = ["one", "two", "three", "four"];
count.shift();
console.log(count);
Output:
["two", "three", "four"]
That's it for today, Will continue....
Written By -Santosh Kumar Verma