In this tutorial, you will learn how to add element or item at first or beginning and last or ending of an array in javascript.
javascript has two inbuilt functions name unshift() and push(), which is used to add elements or items at first or beginning and last or ending of an array in javascript.
This tutorial has the purpose to explain how to add element or item at first or beginning and last or ending of an array in javascript using these unshift and push functions. Also, we will explain definition, syntax, parameters, with examples.
In this tutorial, we will show you two methods with its definition, syntax, parameters with examples to add element or item first or beginning and last or ending of an array javascript.
You can use the javascript unshift() method to add elements or items first or beginning array in javascript.
Definition:- The javaScript unshift() method adds new items to the first or beginning of an array. and it will return the new length of array.
array.unshift(element1, element2, ..., elementX)
Parameter Description
element1, element2, …, elementX Ii is required. The element(s) to add to the beginning of the array
Consider, we 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 );
["zero", "one", "two", "three", "four"]
You can use the javascript push() method to add the elements or items from the last or end of an array.
Definition: – The javaScript push() method is used to add a new element to the last or end of an array.
array.push( element1, element2, ..., elementX )
Parameter Description
element1, element2, …, elementX Ii is required. The element(s) to add to the array
Consider, we 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 );
["one", "two", "three", "four", "five"]
#javascript #programming