a shot of dev knowledge

Related tags

What are some interview questions related to Javascript arrays?

Arrays are one of those appealing topics in any programming language, and almost all interviewers tend to ask one or two questions about them. 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 clear idea of what arrays are and 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 in a similar way to how you may keep your clothes in a drawer.

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

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:

Alt Text

However, my aim in writing this piece is to address one very common question asked during web developer interviews that is related to the insertion/deletion phenomenon of arrays.

The interviewer may ask, "What array methods can be used to insert/delete in an array, and which is the better ones?

The first part of the question is pretty simple, and you can answer it straight away:

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 questionwhere you have to judge which method is better is a little tricky. We can answer this question by finding the number of operations – the one which takes fewer operations will be our answer. For example, in the following array,

let fruits = ['Apple', 'Orange', 'Blueberries']

I want to insert one more fruit, but adding the fourth item to the beginning of the array (hence using unshift method) will cause all the elements to re-index, and it will require more effort. However, if we use the push method, then the fourth item will be added straight to the end, and none of the other items will be disturbed. The same goes for the deletion theory; hence, we can conclude that push/pop is better and faster to use than shift/unshift while working on really large arrayshave thousands and thousands of records.

That’s all folks… Happy coding…

Related tags

RELATED COURSES
View all Courses
Related Courses
Related Courses
View all Courses

Keep Exploring