Search code examples
javascriptarraysshift

JavaScript: What is the logic behind the 'shift' method?


Basically, how do you return AND remove the first element of an array WITHOUT using the shift() OR splice() methods(or any other methods for that matter)?

thanks in advance!


Solution

  • What is the logic behind the 'shift' method?

    It's fully described in the specification.

    Basically, how do you return AND remove the first element of an array WITHOUT using the shift() OR splice() methods(or any other methods for that matter)?

    I can't see any good reason for such a restriction, but you can use a loop to manually assign each entry the value of the one above it (starting at the end) until the index you want to change, and then set the length of the array to one less. Something vaguely like this (I'm sure this is not a complete implementation of what shift does):

    Live example | Live source

    var n;
    for (n = theArray.length - 2; n >= removeAt; --n) {
        theArray[n] = theArray[n+1];
    }
    --theArray.length;
    

    Altering the length property of an array will remove any elements that no longer fall within the length.

    You can also remove an element without altering the length of the array, using delete:

    delete theArray[removeAt];
    

    The array's length will be unchanged, but it will no longer have an entry (at all) at that location. It becomes sparse (if it wasn't already). This works because the delete statement removes properties from objects, and untyped JavaScript arrays are really just objects.