Is ‘list’ and ‘array’ different in Javascript

Arrays are a a powerful and comprehensive tool of Javascript. They are very intuitive to use and you can do almost everything with it. However, there are important differences between arrays in Javascript and other mainstream languages. Knowing them will help you unleash their true potential.

In this article we will go through the important aspects of arrays that are imperative to every JS developer and we will see the variety of usages they have.


Arrays are just regular objects

In Javascript, there are only 6 data types defined – the primitives (boolean, number, string, null, undefined) and object (the only reference type). Arrays do not belong to this list because they are objects as well. This is a common confusion among developers who assume that arrays are a special data type in Javascript.

The items in the array are nothing more than properties of that objects. You can use any name as property for an objects, including numbers or even empty string. However, if the property name is not a valid identifier (doesn’t start with a letter), you can only access it through and not .

So nothing stop us from taking an object and declaring properties like 0, 1, 2 and so on and accessing through , and so on. You don’t need a special data type for doing that in Javascript.

So you may ask: What is special about array object then?

An array has, alongside its elements, a special property named and a generous collection of methods for manipulating the elements. They represent the real power of arrays. You can search, sort, delete, insert and even simulate behavior of other collection data types, like queue and stack.

Remember:

  • arrays are normal objects and their elements are properties with names 0, 1, .. etc.
  • arrays also have a special properties lenght and many function that can manipulate the elements

Declaring an array

Javascript’s elegance owes a lot to its concise literal syntax for the most common building blocks: object, functions and array. A literal is the best way to express an array:

There is an alternative to that, the Array constructor:

Setting aside the aesthetics, there some subtle things you have to care about when using the array constructor. Since Array is a global variable, it can be modified somewhere else in the script so it may not behave as you expected.

One other issue is that if the Array constructor gets only one numerical argument, it will create a list with no elements but with length equal to that argument. So is identical to but it’s not the same thing to .

It is possible to omit the new operator when using the Array constructor. It has the same result so or simply are doing the same thing.

Remember:

  • use array literals instead of the Array constructor
  • the Array constructor behaves differently if its only argument is a number

Detecting an array

Truly determining whether a given object is an array has been one of the classic problems in Javascript.

When dealing with a single page, a single global scope and therefore a single Array global object things are easy:

The problem with is that it assumes a single global execution context. Having multiple frames means multiple contexts and more than one Array global object. ECMAScript 5 come with the solution by introducing the method . It’s not affected by the number of global scopes. If you support ECMAScript 5 in your project, this is the best solution.


The property

What is important to know about is that when you access it, it simply returns the value of the biggest index + 1. This may seem odd, but the big advantage is that it’s very efficient. You won’t have to worry about performance when using it, because the elements are not counted at all. Whenever you add a new element, the value of length will be updated.

Also, you can manually set the value of it. You can truncate the array be setting a smaller length. A convenient way to clear an array is to set the length to 0.

Remember:

  • length simply returns the biggest index of the array + 1 –
  • you can clear the array by setting the length to 0

Since length simply returns the biggest index + 1, it’s value becomes irrelevant if you add a bigger index to the array.

It is a bad practice to do that. This is one of the downfalls of the array being so versatile. A bad code can cause ugly side effects.

Remember:

Don’t change the properties of an array like a regular object. Always rely on the methods provided to operate on its elements.


Array methods

It’s time to finally see them in action!

Any array object has access to a set of methods trough Array.prototype. Since we are talking about a global object, these methods can be altered. It is strongly advised against doing that. Modifying the will affect all the arrays in that global context.

However, I often encounter situations where the prototype scope was augmented by adding other helper functions to Array.prototype. For example, by default there is no method to return the first element of the array (without deleting it). You can add your own custom method:

And now every array in our global scope has access to the first() method. This may be convenient in some situations, but is generally a bad idea. If you modify a prototype, there is always the possibility to clash with other code from your program.

I compile below a list of methods that I consider important and worth to be remembered. It is a good practice to walk through all of them and practice in parallel.

Of course, nobody knows by heard all the details about them, but once you understand the behavior, you know where to search when you need it.


LIFO behavior (stack)

LIFO stands for Last-In-First-Out and represents a stack. Imagine a pile of plates. The last plate you added is the one on top of the pile and it's the only one you can take back. In a stack, there are 2 possible operation: add on top of the stack and remove the last element added from the stack

Functions that allow you to use the array as a stack:

  • -- adds an element v at the end of the array (at index length) --returns the new length of the array
  • --removes the last element --returns the element that was deleted

FIFO behavior (queue)

FiFo stands for First-In-First-Out. Imagine a queue of people standing in line at the store. The person that came first will be the one served. The last person that join the queue will have to wait for all other people to leave before he will be served. A queue in computer programming is similar: the add operation puts an element at the end of the queue and remove operation deletes elements from the start of the queue

  • – returns the first item of the list and deletes the item
  • – see above

Reverse FiFO

  • – adds one or more elements to the beginning of an array and returns the new length of the array
  • – see above

Reordering methods

The function creates a duplicate of the original array and reverse the order of the elements. Again, the original array will not be affected.

Sorts the elements by string comparison. This may be a source of confusion when we try to sort a list of numbers and get an unexpected result. The function, by default, converts the elements to strings (using ). So an array like this will be sorted because the string '10' is bigger than '3'. Of course, string comparison is not always the desired case. The function takes an optional parameter, a comparison function, which will replace the default string comparison. The function takes 2 parameters as arguments - and - and should return if they are equal, a positive value if element1 is bigger and a negative value otherwise. The easiest way to make numeric comparison is to have a function which returns - . The result will be a reference to the new sorted array.


Manipulation methods

Creates a new array based on the elements in the current array. It's important to know that the original array is not altered. The operation is made on the copy of that array. accepts any number of arguments which will be added at the end of the array. Using it without arguments is a elegent way to clone the initial array.

Similar to , slice creates a copy of the array and extracts a subsequence of it. Used with no parameters, it returns a copy of the original. With one argument - -, returns all elements from that index to the end. Additionally, it can be used with 2 arguments - and , in which case it will return all elements in that interval (excluding the one from last_index).

The function can be used with a negative value as parameter. In this case, the start index will be counted from the end of the array -

Splice() has very similar use cases like and , the only difference is that the operation is made on the original array.

It's a destructive method, you won't be able to revert it, so be careful to that when using it.

It can take more arguments . In this case, starting from , it will delete the number of items specified on the second argument. The elements will be added, in this order to the array. Basically, you replace a number of items with the elements you provide.