Question about arrays

this might be a stupid question, but why would I need to use functions like .push, .shift, etc when I can just edit the array I’ve already created

You can’t really dynamically increase or decrease the size of an array cleanly without push, shift, etc. You would have to manually re-index the entire array if you wanted to add or remove a new element anywhere but the end.

All that manual re-indexing and can be pretty verbose and often less efficient that just letting JavaScript do it for you.

Also, why fight conventions? You want write code that generally looks like code that other people would write and understand when you work on projects with others.


Take it from someone who codes a bunch of C - if your programming language has higher level array manipulation and management functionality, you want to take advantage of that functionality. You get cleaner, faster, more readable code in the end.

2 Likes

Like @JeremyLT said if you do certain things to an array it will cause every element to be reindexed, and that takes a lot more time than just appending something to the end of your array so when possible it is more efficient to not add anything to an array unless that thing is going to the end. You will absolutely have to add things to an array that will not be on the end and in that case expect it to take more time than just pushing something onto an array. Built in functions are typically the most efficient way to do that task so if a built in method exist, and it does the job you want you should use it because a lot of the time the browser will have made optimizations just fo that built in function.

2 Likes
function unshift (array, ...args) {
    //array is the array you wish to append things to the front of
    //args is an array of all the arguments but the first argument
    const len1 = array.length;
    const len2 = args.length;

    for (let i = len1; i > -1; i--) {
        array[i + (len2)] = array[i];
    }

    for (let i = 0; i < len2; i++) {
        array[i] = args[i];
    }
    array.length--;
    return array.length;
}

While I would not normally write a function like this, this is what I imagine unshift is doing behind the scenes, or something close to it, and as you can see that is a lot more work than writing array.unshift(1,2,3).

2 Likes