Hello Today i will be discussing about inbuilt unshift() and shift() method of Arrays.
Let's get started...
Unshift - It is used to insert an element at the start of the array.
shift - It is used to remove the first element from the array.
Code Example -
const array = [1,2,3,4,5];
const array2 = ["This","is","array2"]
array.unshift(6) //single element insertion
array.unshift(7,8,9) // multiple element insertion
array.unshift("BOOTSTRAP5") // string element insertion
array.unshift("TAILWINDCSS","REACT JS") //multiple string element insertion
array.unshift([10,11]) // number array insertion
array.unshift(["NODE JS","MONGO DB"]) // string array insertion
array.unshift([[12,13],[14,15]]) // 2-d array insertion
array.unshift({name:"shubham",age:21}) // Object insertion
array.unshift(array2) // array stored in a variable then inserted
array.unshift(undefined,null) // undefined and null insertion
array.unshift(true,false) // Boolean insertion
array.unshift(array) // [Circular *1]
console.log(array)
array.shift() // pop out the first element
array.shift() // pop out the first element
console.log("\n\nAfter shifting 2 times")
console.log(array)
Output -
<ref *1> [
[Circular *1],
true,
false,
undefined,
null,
[ 'This', 'is', 'array2' ],
{ name: 'shubham', age: 21 },
[ [ 12, 13 ], [ 14, 15 ] ],
[ 'NODE JS', 'MONGO DB' ],
[ 10, 11 ],
'TAILWINDCSS',
'REACT JS',
'BOOTSTRAP5',
7,
8,
9,
6,
1,
2,
3,
4,
5
]
After shifting 2 times
[
false,
undefined,
null,
[ 'This', 'is', 'array2' ],
{ name: 'shubham', age: 21 },
[ [ 12, 13 ], [ 14, 15 ] ],
[ 'NODE JS', 'MONGO DB' ],
[ 10, 11 ],
'TAILWINDCSS',
'REACT JS',
'BOOTSTRAP5',
7,
8,
9,
6,
1,
2,
3,
4,
5
]
- As you can see we can insert many tyes of elements at the first index in the array.
- At the last insert, we have pushed the array itself and it returned "[Circular *1] , Circular reference is a references where an object references itself directly or indirectly through an object.
- After using shift() two times, the first two elements are removed.
THANK YOU FOR CHECKING THIS POST
You can contact me on -
Instagram - https://www.instagram.com/supremacism__shubh/
LinkedIn - https://www.linkedin.com/in/shubham-tiwari-b7544b193/
Email - shubhmtiwri00@gmail.com
^^You can help me by some donation at the link below Thank you👇👇 ^^
☕ --> https://www.buymeacoffee.com/waaduheck <--
Also check these posts as well
https://dev.to/shubhamtiwari909/js-push-and-pop-with-arrays-33a2/edit
https://dev.to/shubhamtiwari909/tostring-in-js-27b
https://dev.to/shubhamtiwari909/join-in-javascript-4050
https://dev.to/shubhamtiwari909/going-deep-in-array-sort-js-2n90
Top comments (0)