r/JavaScriptTips • • Jun 30 '22

How does javascrip shift and unshift work?

I saw a picture on the difference between shift and unshift. This is the image https://linksharing.samsungcloud.com/94oIHLFPfnD3

Now I have no knowledge on javascript but it had me thinking.... if unshift ".unshift()" returns the data back into the array. Then where is that shifted data (Deleted)sent when you use ".shift()". Is it stored into ram? Can't be because javascript runs on the web I believe. Database? No I don't have a database and I tried it. Where is the so called "recycle bin" located?

7 Upvotes

11 comments sorted by

2

u/[deleted] Jun 30 '22

This pic isn't quite right. Unshift works with an input to insert it at the beginning of an array.

1

u/ApartSource2721 Jun 30 '22

I saw it on Instagram. So I guess it's saying the correct thing but they did not explain what is going on?

1

u/ApartSource2721 Jul 01 '22

Ok everyone I understand now. Thanks for the clarity!!

1

u/[deleted] Jun 30 '22

I’m pretty new to JS but I believe you can set .shift to a variable and call it then. I may be wrong though but I think I saw someone do that once

3

u/ApartSource2721 Jun 30 '22

It's not a matter of variables I just want to know where the data is temporarily stored when u shift it out of the array. Because the fact that you can bring it back with unshift. Then it must he stored somewhere. Hmmmmm. Please help upvote

1

u/[deleted] Jun 30 '22

Ahh, good point! Upvoted, hopefully we both get an answer!

1

u/Waffleeater_153 Jun 30 '22

Shift() removes an item from the beginning of the array and shifts the array over one index If you have an array [7,9,22] shift() will change the value of the array to be [9,22] Unshift() only works with an input and it adds the input into the beginning of the array. Example: [11, 17] Unshift(8) Would make the array [8, 11, 17]

2

u/ApartSource2721 Jun 30 '22

So unshift does not bring back to value that was removed? Let's say we have [9,10,11] and we use "shif()" ok 9 is gone. If we use "unshift()" won't 9 come back?

2

u/Waffleeater_153 Jun 30 '22

No they’re 2 seperate functions. One removes from the front of an array and the other inputs a value into the front. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift

1

u/irukadesune Jun 30 '22

I think the curiosity is solved here. In summary .unshift method requires at least 1 parameter to input what value you want to put inside the array. Which means the image you saw on Instagram is wrong and kind of misleading.