18
loading...
This website collects cookies to deliver better user experience
square bracket []
notation. Array.unshift()
method adds elements to the beginning
of an existing array. The following is an example of adding elements using this method:let fruits = ["Watermelon","Grapes","Guava"];
console.log(fruits.length); //output 3
fruits.unshift("Mango","Apple","Orange");
console.log(fruits);
//output: [ 'Mango', 'Apple', 'Orange', 'Watermelon', 'Grapes', 'Guava' ]
console.log(fruits.length); //output: 6
.unshift()
method took 3 parameters and added them in the beginning of the array. let fruits = ["Watermelon","Grapes","Guava"];
console.log(fruits.length); //output: 3
let newFruits = ["Mango","Apple","Orange"];
fruits.unshift(newFruits);
console.log(fruits);
//output: [
[ 'Mango', 'Apple', 'Orange' ],
'Watermelon', 'Grapes', 'Guava'
]
console.log(fruits.length); //output: 4
.unshift()
method took the newFruits variable as it's parameter and added the array stored in it.Array.push()
method adds elements to the end
of an existing array. The following is an example of adding elements using this method:let fruits = ["Watermelon","Grapes","Guava"];
console.log(fruits.length); //output 3
fruits.push("Strawberry","Blueberry","Pineapple");
console.log(fruits);
/* output: [ 'Watermelon','Grapes','Guava',
'Strawberry',Blueberry','Pineapple' ] */
console.log(fruits.length); //output: 6
.push()
method took 3 parameters and added them to the end of the array. The array length is also increased from 3 to 6. .unshift()
method, .push()
can also add an array or an Object or both to the end of the existing array. Here, we will add an Object to the end of the array for example:let fruits = ["Watermelon","Grapes","Guava"];
console.log(fruits.length); //output 3
let newfruits = {"S" : "Strawberry", "B": "Blueberry", "P" : "Pineapple"};
fruits.push(newfruits);
console.log(fruits);
/*output: [
'Watermelon',
'Grapes',
'Guava',
{ S: 'Strawberry', B: 'Blueberry', P: 'Pineapple' }
] */
console.log(fruits.length); //output: 4
.push()
method took the newFruits variable as it's parameter and added the Object stored in it.let fruits = ["Watermelon","Grapes","Guava"];
console.log(fruits.length); //output 3
fruits.unshift("Mango", "Apple", "Orange");
fruits.push("Strawberry", "Blueberry", "Pineapple");
console.log(fruits);
console.log(fruits.length); //output: 9
/*output: [
"Mango", "Apple", "Orange",
"Watermelon","Grapes","Guava",
"Strawberry", "Blueberry", "Pineapple"
]
*/