Feed aggregator

Mnemonic for Shift() and Unshift()?

Hacker News - Thu, 03/28/2024 - 1:40am

JavaScript push() and pop() are intuitive method-names because they come from the context of using an array as a "stack". You can "push" things to a stack meaning a new item is added as the new last element of the array. push() pushes a new element into the array. Pop() pops one off it.

shift() and unshift() on the other hand I always had trouble with. One of them adds a new element to the front of the array and the other removes and returns the 1st element. But which is which? I can google the answer but would be nice if I didn't have to google. And worse, sometimes I got confused between the two and used shift() where unshift() should have been used => Error,, stack overflow!

So I googled for "Mnemonics for shift() and unshift()", and found an entry on Stack Overflow. But that question was "Closed because the answers are opinion-based". I looked at the answers available but none of them struck me as particularly memorable.

Now after years of struggling with this confusion I think I've come up with a mnemonic I can live with:

Word "shift" is shorter than the word "unshift". Therefore shift() makes the array shorter.

Word "unshift" is longer than the word "shift". Therefore unshift() makes the array longer.

I know it doesn't really explain it, but it is a rule I can remember. I would appreciate hearing how anybody else remembers when to use shift() and when to use unshift().

Comments URL: https://news.ycombinator.com/item?id=39848102

Points: 1

# Comments: 0

Categories: Hacker News

Pages