JavaScript Add Element to Beginning and Ending of Array

To insert or add element to beginning and ending of array JavaScript; Through this tutorial, i am going to show you how to add element at beginning or start and at end or last of an array in JavaScript.

The JavaScript unshift() and push() are used to add elements or items at first or beginning and last or ending of an array in javascript.

JavaScript Add Element to Beginning and Ending of Array

  • JavaScript Add Element to Beginning or Starting of array
  • JavaScript Add Element to Ending or Last of array

JavaScript Add Element to Beginning or Starting of array

Using the javascript unshift() method, you can add elements or items first or beginning array in javascript.

Syntax of javaScript unshift() method

The following syntax of unShift() method as shown below:

 array.unshift(element1, element2, ..., elementX)

Parameters of javaScript unshift() method

ParameterDescription
element1, element2, …, elementX Ii is required. The element(s) to add to the beginning of the array

Example 1 – Add element start or beginning of an array javaScript

Let, you have an array that’s the name arrNum, and it contains four elements inside it, see below:

var arrNum = [
   "one",
   "two",
   "three",
   "four"
 ];

If you want to add element start or beginning of an arrNum array. So you can use the unshift() method of javaScript like below:

var arrNum = [
   "one",
   "two",
   "three",
   "four"
 ];
 arrNum.unshift("zero");
 console.log( arrNum );

Output of the above example:

["zero", "one", "two", "three", "four"]

JavaScript Add Element to Ending or Last of array

Using javascript push() method, you can add the elements or items from the last or end of an array.

Syntax of javaScript push() method

See the following syntax of push() method; as shown below:

 array.push( element1, element2, ..., elementX )

Parameters of javaScript push() method

ParameterDescription
element1, element2, …, elementX Ii is required. The element(s) to add to the array

Example 1 – javascript add the element to last or end of an array

Let, you have an array that’s the name arrNum, and it contains four elements inside it, see below:

var arrNum = [
   "one",
   "two",
   "three",
   "four"
 ];

If you want to add the single item into the arryNum array. So you can use the push() method of javaScript like below:

var arrNum = [
   "one",
   "two",
   "three",
   "four"
 ];
 arrNum.push("five");
 console.log( arrNum );

Output of the above example:

["one", "two", "three", "four", "five"]

More JavaScript Tutorials

Recommended:-JavaScript Arrays
Recommended:-

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *