DEV Community


Posted on

Common Interview Question -- Javascript Arrays

Arrays are one of those appealing topics in any programming language that almost all the interviewers tend to ask one or two questions about. In this article, I will be talking about Javascript arrays and some very frequently asked questions related to them.

First of all, you should have a very clear idea about what arrays are and what is the purpose of using them in your code.
To be precise, arrays are like the containers of your data, they keep the information/data in an ordered form just like you keep your clothes in a cupboard in an organized manner:
Alt Text

You can find all the relevant documentation about all the array methods in the MDN docs here:

Also, it is not always possible to remember all the methods and their functionalities since there are quite a lot of them therefore I would recommend keeping this Javascript arrays cheatsheet handy for quick reference found at
Alt Text

However, my aim of writing this piece is to address one very common question asked during web developer interviews and it is related to the insertion/deletion phenomenon of arrays.
The interviewer may ask which are the array methods used for inserting/deleting in an array and which are the better ones?

The first part of the question is pretty simple and you can answer it straightaway...The two methods used for insertion/deletion are push/pop and shift/unshift.
We can illustrate the functionality of these methods as follows:
Alt Text

However, the second part of the question is little can you judge which is one is better and which is not..we can answer this question in terms of number of operations, the one which takes lesser operations will be better. For example we have the following array:

let fruits = ['Apple', 'Orange', 'Blueberries']
and I want to insert one more fruit to this array, adding the fourth item to the beginning of the array (hence using unshift method) will cause all the elements to re-index and hence more effort required however if we used the push method then the fourth item will be added straight to the end and none other items will be disturbed, same goes for the deletion theory hence we conclude that push/pop is better and faster than shift/unshift while working on really large arrays having thousands and thousands of records.

That's all folks..
Happy coding...

Top comments (0)