In this article, we’ll have a look at quite a few JavaScript quirks.

Some useful tips and tricks in JavaScript Image by CodingExercises

Using the delete method on an array member

If you use the delete method on an array member, this doesn’t erase the value, it just replaces it with undefined:

var arr = ['one','two','three','four'];
delete arr[0];
console.log(arr); // returns: [undefined, 'two', 'three', 'four']

Does a value exist in an array?

We check using the indexOf method:

var arr = ['one','two','three','four'];
arr.indexOf('five'); // returns: -1
arr.indexOf('four'); // returns: 3

When it returns -1, it means it can’t find the specified member in the array.

Alternatively, the includes method returns true if a matching member is found, and false otherwise:

['one','two','three','four'].includes('one'); // returns: true
['one','two','three','four'].includes('five'); // returns: false

You can pass another argument to includes to specify which member of array to start to search from:

['one','two','three','four'].includes('two', 1); // returns: true
['one','two','three','four'].includes('two', 2); // returns: false

Use Array.length to find the last member of array

Since Array.length counts an array from 1, and arrays are zero-indexed, it’s easy to get the last member of an array:

arr[arr.length - 1]; // returns: "four"

Use Array.length to quickly trim an array

You can change the length of an array on the fly, using Array.length property, like this:

arr.length = 2;
console.log(arr); // returns: [undefined, "two"];

Manipulating arrays with pop

The pop() method is used to remove an item from an array. For example, on Google search results, we can get the all the h3 search results’ headings into an array like this:

var arr = [...document.getElementsByTagName('h3')];
arr.length;
arr.pop();

On the second row in the above code, we check the length of the array.

On the third row, we removed a member that was placed in the last position of arr array.

On the fourth row in the above code, we check the length of the array again - now its’ length is smaller by one.

Manipulating arrays with push

The push method is the opposite of pop:

var arr = [];
arr.push('one');
arr.pop;

Manipulating arrays with shift

The shift method is like pop, only it removes items from the start, not the end:

var arr = ['one','two','three','four'];
arr.shift();
arr; // returns: ['two','three','four']

Manipulating arrays with unshift

The unshift method is like push, only it adds items from the start, not the end:

var arr = ['one','two','three','four'];
arr.shift();
arr.unshift('one');
arr; // returns: ['one','two','three','four']

Manipulating arrays with Array.slice and Array.splice

The slice method returns a specified slice of the source array.

For example, we want to extract only the last two items from the below array:

var arr = ['one','two','three','four'];
arr.slice(2,3); // returns: ['three']
arr.slice(2); // returns: ['tree','four']
arr.slice(2,4); // returns: ['tree','four']

The Array.slice method is non-destructive.

The splice method does two things:

  1. It removes specified items from an array
  2. It optionally puts new items in the removed slots

An example of removing the first entry in an array:

var arr = ['one', 'two', 'three', 'four'];
arr.splice(0,1); // returns: ['one']
arr; // returns: ['two','three','four']

The first argument to the splice method specifies where to start splicing. The second argument specifies how many items to splice. The remaining arguments represent the optionaly new items to add in the place of removed slots.

Note that slice is non-destructive, and splice is destructive.

Destructuring Arrays

We can group multiple values in an array.

Thus, instead of writing:

var one = 'one';
var two = 'two';
var three = 'three';
var four = 'four';

…we can write:

var arr = ['one','two','three','four'];

But what if we want to go the other way round? To take members of array and make each of them individual variables?

That’s where array destructuring comes in:

var [one,two,three,four] = arr;

Now the variables are available individually:

console.log(one); // returns: "one"

You can also skip values, like this:

var [_1, , ,_4] = arr;
_1; // returns: "one"
_2; // returns: Uncaught ReferenceError: _2 is not defined at <anonymous>:1:1
_4; // returns: "four"

You can use the rest operator, ..., to get back a sub-array:

var [_one, ...others] = arr;
console.log(_one); // returns: "one"
console.log(others); // returns: ['two','three','four']

Concat two arrays together

Let’s say we’ve got these two arrays:

var arr1 = ['one'];
var arr2 = ['two'];

We can combine them like this:

arr1.concat(arr2); // returns: ['one','two']

…but if we do this:

arr1; // returns: ['one']

Obviously, the concat method doesn’t update arr1. It’s an easy enough fix though:

arr1 = arr1.concat(arr2);

We can also concat two arrays using the spread operator ..., like this:

var _arr1 = ['one','two'];
var _arr2 = ['three','four'];
var _arr1 = [ ..._arr1, ..._arr2 ];
_arr1; // returns: ['one','two','three','four']

Convert an array to a string

We can do this with the help of the join method.

var arr = ['one','two','three','four'];
arr.join(); // returns: "one,two,three,four"

If you’re a musician, you might wanna return this:

arr.join(' and '); // returns: "one and two and three and four"

Flipping the order of items in an array

The destructive reverse method makes this possible:

var arr = ['one','two','three','four'];
arr.reverse(); // returns: ['four','three','two','one']

Sorting arrays with Array.sort

It’s simple:

var arr = ['one','two','three','four'];
arr.sort(); // returns: ['four','one','three','two']

It’s also a destructive method.

There can be some unexpected behavior: capital letters are sorted before small letters:

var arr = ['one','One','two','Two'];
arr.sort(); // returns: ['One','Two','one','two']

Additionally, numbers are sorted based on the first digit in each item:

[300,20,1].sort(); // returns: [1,20,300]
[100,20,3].sort(); // returns: [100,20,3]

Thus, the sort method, out of the box, is probably not the best tool to use.

However, it can still be used in certain situations, as long as we’re aware of its limitations.

Next, we’ll see an example of solving a simple problem with arrays and some array methods, including sort.

Exercise: Sort a todo list

Let’s say you have the following text in a txt file:

1. take out trash
3. learn js
2. go shopping
5. have some rest
4. watch a movie

How do you organize the above text using JavaScript, so that it’s ordered by numbers?

Here’s the solution.

First, we add the text:

var todos = `1. take out trash
3. learn js
2. go shopping
5. have some rest
4. watch a movie`;

Next, we replace the newline characters with a character that doesn’t exist in the string, then we split the string using the “weird” character.

todos = todos.replace( /\n/g, "|" ).split( "|" )

Next, we’ll use sort:

todos = todos.sort();

That’s it, we get the result we wanted:

["1. take out trash", "2. go shopping", "3. learn js", "4. watch a movie", "5. have some rest"]

Additional Exercise: Reverse the order of array

To make the order of todos descend rather than ascend, we can use the reverse method:

todos = todos.reverse()
// returns: (5) ["5. have some rest", "4. watch a movie", "3. learn js", "2. go shopping", "1. take out trash"]

We can revert the array back to string:

todos = todos.join(",")
// "4. watch a movie,5. have some rest,2. go shopping,3. learn js,1. take out trash"

And now we can add a space after the , character:

todos.replace(",", ", ")
// returns: "5. have some rest, 4. watch a movie,3. learn js,2. go shopping,1. take out trash"