Ask HN: Mnemonic for shift() and unshift()?
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().