The JavaScript an Array function

The JavaScript Array object is a global object that is used in the construction of arrays; which are high-level, list-like objects. The Array object lets you store multiple values in a single variable. It stores a fixed-size sequential collection of elements of the same type.

Create an array object
var books = ['C', 'Javascript', 'Java'];

We can easily get number of element in an array object: 
 console.log(books.length); // 3

Looping over an Array we can easily loop the an array element using loop statement.

books.forEach(function(item, index, array) {
console.log(item, index);
});
// C - 0, Javascript - 1, Java -2
Adding new element at the end of an Array

var newLength = books.push('C++');

 

2. push(): Adds one or more elements to the end of an array and returns the new length of the array.

3. splice() method:

The splice() method adds/removes items to/from an array, and returns the removed item(s) and change the content of an array, adding new elements while removing old elements. Splice method adds new element to existing an array and remove an element from to existing array and then add the removed element to new an array.

Syntax
array.splice(index, howMany, [item1][, …, itemN]);

Where index − Index at which to start changing the array.  howMany − total number of old array elements to remove. If howMany is 0, no elements are removed.  item1, …, itemN − Optional, and the elements to be added to the array. If you don’t specify any elements, splice simply removes the elements from the array. 

Note: This method changes the original array.

<body>
<p>Click the button to add and remove elements.</p>
<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
var companies = ["Apple", "Google", "Facebook", "IBM"];
document.getElementById("demo").innerHTML = companies;

function myFunction() {
    companies.splice(2, 1, "Infosys", "TCL");
    document.getElementById("demo").innerHTML = companies;
}
</script>
</body>

In this example, we are removing one element at second index and adding two new an element at companies array index 2. The resulting array element of companies is Apple,Google,Infosys,TCL,IBM, and where second element Facebook is remove from an array list.

Example 2:  Here we are removing the element from the existing array and add the removed element to a new array called sliced.

<body>
<p>Click the button to add and remove elements.</p>
<button onclick="myFunction()">Try it</button>

<p id="demo"></p>
New sliced array
<p id="sliced"></p>

<script>
function myFunction() {
	var oldArray = ['zero', 'one', 'two', 'three'];
	var sliced = oldArray.splice(2, 3);
	document.getElementById("demo").innerHTML = oldArray;
	document.getElementById("sliced").innerHTML = sliced;
} 
</script>
</body>

Output of the above code, oldArray :[ “zero”,”one”] and new sliced  : “[two”,”three”]

 

To remove an item from the list