DEV Community

Leslie Tang
Leslie Tang

Posted on • Updated on

7 Beginner's Tricks in Using Arrays in JavaScript

References:

  1. JavaScript: The Good Parts by Douglas Crockford, 2008. Page 58-64.
  2. Mozilla JavaScript Reference

Note: Beginner is a relative and subjective descriptive term. I define "tricks" as ways of writing JavaScript to manage arrays. In my case, the ideas and concepts illustrated in the book: "JavaScript: The Good Parts" are things that I didn't realize before.


1. Arrays vs Objects

JavaScript Arrays are essentially objects. In the beginning, I simply assumed that both are the same thing; but in reality, arrays inherit from Array.prototype. Which gives arrays access to some useful methods.

In his book, Crockford mentioned a Rule of Thumb: "Use Arrays when property names are small sequential integers, else use objects".

I guess the rationale is to ease the retrieval of data. For example, rankings data would benefit from being stored in an Array rather than an Object. A simple loop would enumerate the rankings in order. On the other hand, it would make sense to store stats about the rankings in an object with properties such as "Best Timing", "Contributions", "Identity", etc.

2. How to Differentiate Arrays and Objects

Using typeof operator, we observe that an array would be flagged as object. I would imagine that verification of whether an array is indeed an array or just an object would be useful in writing unit tests.

The below is a code snippet from the book which allows us to check if the variable is indeed an Array.

var myArray=  [4, 8, 15, 16, 23, 42];
Array.isArray(myArray); // Return true if value is an Array
Enter fullscreen mode Exit fullscreen mode

3. Enumeration

Since arrays are objects, we could use for...in to enumerate properties of an array. The problem of doing so is that the prototype chain would be traversed; leading to unrelated properties being enumerated.

The suggested way of enumerating values in an array is to use a for of loop.

for (const value of myArray){
    console.log(value);
}
Enter fullscreen mode Exit fullscreen mode

4. Augmenting Array with New Methods

We can augment Array.prototype to introduce new behaviors to all arrays in the program. Let's say we want to add some_function that can be used by all Array objects, we can do so as shown below:

Array.some_function = function () {
    // insert code of the function
    return some_value;
};
Enter fullscreen mode Exit fullscreen mode

To introduce new behavior to specific arrays, we simply add a new property to them. For example, let's say we want to add a total function to a data_array, we can do so as shown below:

data_array.total = function(){
    // insert code here to sum up values in the array
    return total;
}
Enter fullscreen mode Exit fullscreen mode

5. Array Initialization

By default, JavaScript Arrays are not initialized. For example var newArray = [] would simply create an empty array. Attempting to access newArray[94] would return undefined.

Let's say we want to initialize the array with value 0, we can simply write a for loop to iterate through the array and assign each index with the value. But having to do so each time you want to initialize an array would lead to code repetition. A smarter way is to create an Array function as shown:

Array.init = function (size, initial_value) {
    var i;
    var array = [];
    for (i = 0; i < size; i += 1) {
        array[i] = initial_value;
    }
    return array;
};

// Initialize an Array, size 10, with value 0
var zeroArray = Array.init(10,0);
Enter fullscreen mode Exit fullscreen mode

6. Deleting Elements in Array

While we can simply remove an element from an array by using delete myArray[2], doing so would create a "hole" in the array.

One way we can delete elements from an array without leaving holes behind is to use the splice method.

myArray.splice(target_index,number_of_elements);
Enter fullscreen mode Exit fullscreen mode

Splice would remove the desired number of elements starting from the target index as shown above and remove the holes left behind. However, this is done by removing and reinserting the values after the hole to the new slot, which means it might take some time if the array is large.

7. Adding Elements to Array

The first thing that comes to mind is to assign the new element to the end of the array through myArray[myArray.length].

But there is a push method that's available to array that can let us do the same thing.

myArray.push(myElement)
Enter fullscreen mode Exit fullscreen mode

I've ordered the tricks from the most impactful to the least impactful, at least to me. The biggest eyeopener for me is the idea of extending arrays with custom methods as a way to reduce code repetition.

Thank you for reading and I hope that you gained something from this article. 😄




Article Updates:
  • 23 Dec 19. "Point 2: How to Differentiate Arrays and Objects". Replaced original code snippet with Array.isArray(). Credits: @nijeesh4all

  • 23 Dec 19. "Point 3: Enumeration". Replaced original code snippet with for ofloop. Credits: @erezwanderman and DrakeLumen

  • 24 Dec 19. "Point 5. Array Initialization". Replaced original code snippet with Array.fill(). Credits: @yoni12ab

Discussion (13)

Collapse
nijeesh4all profile image
Nijeesh Joshy • Edited on

isnt using Array.isArray() a better approach for checking whether the object is an array or not?

developer.mozilla.org/en-US/docs/W...

Collapse
tangweejieleslie profile image
Leslie Tang Author

Thanks for pointing that out, truth be told, I wasn't aware of Array.isArray().

I wrote this article as a summary of reading "JavaScript: The Good Parts by Douglas Crockford", 2008. Page 58-64. Hence, the reason why the points in the article might not be the best/latest.

Collapse
dannyengelman profile image
Danny Engelman

Not to sound like an old grumpy guy...
Instead of reading a 11 year old article by that old grumpy Crockford

You are better of reading the Array documentation,
and learn all Array methods listed in the left column

developer.mozilla.org/en-US/docs/W...

In general if you want to learn/read documentation,
all you type in Google is: js mdn [topic]

So in this case: js mdn array

Keep on learning!

Thread Thread
nijeesh4all profile image
Nijeesh Joshy

For becoming zero to hero on modern Js mdn is the best resource out there.

Thread Thread
tangweejieleslie profile image
Leslie Tang Author

Thanks for the advice! Really appreciate the feedback. It's critical feedback like this that can help inexperienced newbies like me learn what's truly useful.

I've read that book because it was one of the resources recommended to me, so I've used that as a starting point.

Collapse
hitautodestruct profile image
Yotam

Augmenting Array with New Methods

This is considered a bad practice since you could easily overwrite a native array method. Although if you like spending a few hours looking for bugs, then this is fine :-)

See what happened with mootools.

And also Smooshgate

Collapse
tangweejieleslie profile image
Leslie Tang Author

Thanks for the advice and the examples! It didn't occur to me that such a situation would occur.

Collapse
erezwanderman profile image
erezwanderman

A modern way yo iterate an array if you don't need the index would be the "for of" loop

Collapse
tangweejieleslie profile image
Leslie Tang Author

Thanks for pointing that out!

Collapse
yoni12ab profile image
yoni12ab

5 you can use Array.fill

Array(5).fill(2)

Collapse
tangweejieleslie profile image
Leslie Tang Author

Thanks for pointing that out!

Collapse
schwarcu profile image
Schwarcu

Hi, why are you using var instead of let?

Collapse
dannyengelman profile image
Danny Engelman

You teach people .push
but not .pop .shift .unshift
That is like teaching people to drive in first gear and nothing else