Categories
JavaScript Best Practices

JavaScript Antipatterns — Arrays, JSON, and Regex

Spread the love

JavaScript lets us do a lot of things. It’s sometimes too forgiving in its syntax.

In this article, we’ll look at some antipatterns that we should avoid when we’re defining and using arrays, JSON, and regex.

Array Literals

We can define an array with the Array constructor with array literals.

The constructor has 2 versions. The one argument version is different from the one with multiple arguments.

If we pass in one argument, it’ll create an array with the given length with all empty entries.

If we pass in more than one argument, then an array with the arguments will be created.

For instance, we can create one as follows:

const empty = new Array(5);

or:

const arr = new Array(1, 2, 3);

Array Literal Syntax

The array literal syntax lets us create an array without the array constructor.

For instance, we can write:

const arr = [1, 2, 3];

This syntax is simple and straightforward.

It’s cleaner than using the new operator and the constructor.

Avoid the Array Constructor

Because of the different versions of the array constructor, then we would have issues because of the confusion between them.

If we pass in a floating-point number into the Array constructor, then we get an error.

This is because a floating-point number isn’t a valid length.

For instance, if we have:

const a = new Array(3.14);

Then we get ‘Uncaught RangeError: Invalid array length’.

Check if an object is an Array

Using the typeof operator isn’t useful for checking if an object is an array.

If we write:

console.log(typeof [1, 2]);

we get 'object' on the console log output.

Therefore, we can’t use the typeof operator to check if an object is an array.

We can use the code instanceof Array to check if something is an array.

It may fail in IE when used across frames, but this shouldn’t be an issue most of the time.

So we can use:

[1, 2] instanceof Array

Also, we can use the Array.isArray method, which does work across frames.

We can use it by writing:

Array.isArray(`[1, 2])`

It works across frames and only returns true if it’s actually an array.

JSON

JSON stands for JavaScript Object Notation.

It’s the main data transfer format for JavaScript apps.

It’s just the combination of arrays and the object literal notation.

The only difference between a JavaScript object and a JSON string is that we’ve to wrap keys with double-quotes.

JSON strings can’t have functions or regex literals.

Working with JSON

The best way to work with JSON is to use the JSON.parse method, which is available since ES5.

We can sue it to parse JSON strings to JavaScript objects.

To convert an object to a string, we can use the JSON.stringify method.

For instance, we can use them as follows:

const str = JSON.stringify({
  foo: 1,
  bar: new Date(),
})

Then we get:

"{"foo":1,"bar":"2020-04-20T15:18:51.339Z"}"

as the value of str .

To parse a JSON string, we can write:

const obj = JSON.parse("{\"foo\":1,\"bar\":\"2020-04-20T15:18:51.339Z\"}")

Once an object is converted to a string, then it’ll be converted back to a string.

So we get:

{foo: 1, bar: "2020-04-20T15:18:51.339Z"}

as the value of obj .

Regular Expression Literal

A regex in JavaScript is also an object.

We can create them using the RegExp constructor or a regex literal.

For instance, we can create it as follows:

const re = /foo/gm;

as a regex literal, or:

const re = new RegExp("foo", "gm");

using the constructor.

The regex literal is shorter and we don’t have to think about using the constructor.

So it’s better to use the literal.

If we use the constructor, we’ve to escape quotes and backslashes.

Therefore, it’s hard to read and modify.

To make things simple, we should stick with the literal notation.

Regular Expression Literal Syntax

The regex syntax uses forward slash to delimit them and then we have the modifiers.

They include:

  • g — global match
  • m — multiline
  • i — case insensitive match

The modifiers can be added in any order.

For instance, we can use regex literals in the string replace method:

const str = "abc123".replace(/[a-z]/gi, "");

Then we stripped all the letters our of the string and get 123 .

The regex matches all letters in the string and replaced them with empty strings.

Conclusion

We should use literals to define arrays and regex whenever we can.

Ther literal notations are usually shorter and cleaner.

Also, the Array.isArray method is great for checking if an object is an array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *