Categories
JavaScript Best Practices

JavaScript Best Practices for Writing More Robust Code — Removing Duplicates and Merging Arrays

JavaScript is an easy to learn programming language. It’s easy to write programs that run and does something. However, it’s hard to account for all the uses cases and write robust JavaScript code.

In this article, we’ll look at how to remove duplicate items from an array in a reliable way.

Sets

We can use the JavaScript Set constructor to create sets, which are objects that can’t have duplicate items included.

Duplicate items are determined in a similar way to the === operator, but we -0 and +0 are considered to be different values.

NaN is also considered to the be same as itself for the purpose of determining duplicate items for Set s.

We can create a set from an array as follows:

const set = new Set([1, 2, 3, 3]);

Then we have Set instance that has 1, 2 and 3 as the value of set .

Since a Set is an iterable object, we can use the spread operator to convert it back to an array as follows:

const noDup = [...set];

As we can see, it’s very easy to convert a Set back to an array.

Since the algorithm for determining duplicates is determined in a similar way to the === operator, it works well for removing duplicate primitive values.

However, it doesn’t work well for objects unless they reference the same item in memory.

If we have objects, then the most reliable way to remove duplicates is to convert them to strings and then parse them back to objects.

For instance, if we have the following array:

const arr = [{
  a: 1
}, {
  a: 1
}];

Then we can write the following code to map the array to a string, turn it to a Set , then we can parse the remaining items back to objects as follows:

const set = new Set(arr.map(a => JSON.stringify(a)));
const noDup = [...set].map(a => JSON.parse(a));

In the code above, we have a Set , which is created from array entries that are stringified with JSON.stringify .

Then we use the spread operator to spread the set back to an array and then map the stringified entries back to objects with JSON.parse .

This works well for plain objects that have no methods in them.

If our objects have methods, then we should make sure that each entry reference the same object.

Set s also have methods to make traversing them easier. There’s the entries method to get all the entries as an iterator that returned each entry as an array with the [key, value] structure.

forEach takes a callback to loop through them. The keys and values methods let us get the keys and values respectively.

The clear method removes all items from a set.

It also has the size property to get the size of the Set .

Using the Spread Operator

The spread operator is one of the most useful features that are added recently to JavaScript.

When it’s used with arrays, it can let us make copies of arrays or merge them without calling any methods. This makes our code short and easy to read.

We just put everything in an array with the spread operator and then we get a new array with new items.

Also, it lets us combine items from different kinds of iterable objects into one array.

For instance, we can use the spread operator with multiple arrays as follows:

const arr1 = [1, 2, 3];
const arr2 = [4, 5];
const arr = [...arr1, ...arr2];

Then we get that the value of arr is [1, 2, 3, 4, 5] .

As we can see, the items are added in order into the new array with the spread operator.

Since the spread operator works with different kinds of iterable object, we can spread Map s and Set s into arrays as well:

const arr1 = [1, 2, 3];
const set = new Set([4, 5]);
const map = new Map();
map.set('a', 1);
map.set('b', 2);
const arr = [...arr1, ...set, ...map];

Then we get that arr is:

[
  1,
  2,
  3,
  4,
  5,
  [
    "a",
    1
  ],
  [
    "b",
    2
  ]
]

The Map s are converted to an array with entries that are an array of key and value .

Conclusion

Set s are useful for removing duplicate items from arrays. They can also be converted or merged into arrays.

We can also merge multiple kinds of iterable objects into an array with the spread operator.

Categories
JavaScript Best Practices

JavaScript Best Practices — Arrays

JavaScript is a very forgiving language. It’s easy to write code that runs but has mistakes in it.

In this article, we’ll look at the best ways to work with JavaScript arrays

Don’t Use the Array Constructor Most of The Time

If we’re just defining an array with some entries in it, then we shouldn’t use the Array constructor to do it.

Using the Array constructor is longer, and there are also 2 versions of the constructor.

If we call the Array constructor with one argument, then it’ll create an array with the number of empty slots that are given by the number that we passed in.

If we call it with multiple arguments, then we get an array that has the entries that we passed into the arguments with it.

Also, it can be called with or without the new operator.

Therefore, we should just use an array literal to define an array whenever possible.

For instance, instead of writing:

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

We should write:

const arr = [1, 2, 3];

As we can see, the 2nd example is much shorter and does the same thing.

The only exception for using the Array constructor is to fill an array with the same entries.

We can do that with the Array constructor as follows:

const arr = Array(5).fill(1);

Array(5) returns an array with 5 empty slots, and fill(1) fill those slots with 1’s.

Use Array.prototype.push Instead of Direct Assignment to Add Items to An Array

The array’s push instance method always adds an item to the end of the array.

This is much shorter than assigning the item to the last entry of the array with the bracket notation.

Therefore, instead of writing:

const arr = [1, 2];
arr[arr.length] = 3;

We should write:

const arr = [1, 2];
arr.push(3);

As we can see, it’s shorter and easier to use than using the bracket notation since we don’t have to think about array indexes at all when we call push .

Use the Spread Operator to Copy Arrays

The spread operator lets us copy arrays without using loops. It’s good for making a shallow copy of an array.

For instance, instead of using a loop to copy the array’s entries into a new one as follows:

const arr = [1, 2, 3];
const copy = [];
for (const a of arr) {
  copy.push(a);
}

We can write that all in one line as follows:

const arr = [1, 2, 3];
const copy = [...arr]

As we can see, we didn’t need a loop to make a shallow copy of an array. All we have to do is to use the spread operator.

Rather than using a loop to make a copy, we just use the ... operator to do the same thing in a much shorter way.

Use the Spread Operator to Convert Iterable Objects to Arrays Instead of Calling Array.from

The Array.from is good for converting iterable objects into an array. For instance, we can write the following code to convert a NodeList into an iterable object with it:

const ps = document.querySelectorAll('p');
const arr = Array.from(ps);

In the code above, we get all the p elements on a page with the querySelectorAll method and then convert the returned NodeList object to an array with Array.from .

However, we can do that in a shorter way with the spread operator. We can rewrite our code as follows:

const ps = document.querySelectorAll('p');
const arr = [...ps];

It does the same thing, just we type less to do it.

The only case that Array.from is good for is converting non-iterable array-like objects, which are objects with numerical keys and the length property with an integer as its value.

For instance, we can convert them to an array by calling Array.from as follows:

const obj = {
  0: 'a',
  1: 'b',
  length: 2
}
const arr = Array.from(obj);

In the code above, we passed in the obj object with the keys 0 and 1 and the length property with the value 2. Then when we pass it into Array.from , we have the following array returned:

["a", "b"]

Conclusion

We should use array literals to define arrays instead of using the Array constructor to define arrays most of the time.

The spread operator is useful for copying arrays and converting iterable objects to arrays.

Categories
JavaScript Best Practices

JavaScript Best Practices — Objects

JavaScript is a very forgiving language. It’s easy to write code that runs but has mistakes in it.

In this article, we’ll look at the best way to work with objects in our JavaScript code.

Use Property Value Shorthand

The property value shorthand is a great way to shorten our way that we define our objects.

With it, if the key and value have the same identifier, then we can shorten ut by combining it into one.

For instance, instead of writing the following code:

const x = 1,
  y = 2;

const obj = {
  x: x,
  y: y
};

We can instead write:

const x = 1,
  y = 2;

const obj = {
  x,
  y
};

As we can see, it’s much shorter and easier to read when there’s only one identifier rather than repeating identifiers.

They both set x to 1 and y to 2 within the obj object.

Group Shorthand Properties At the Beginning of the Object

Shorthand properties should be grouped at the beginning of the object so that we can tell that those properties are defined with the shorthand.

For instance, we can write something like the following to define our object:

const x = 1,
  y = 2;

const obj = {
  x,
  y,
  foo: 1,
  bar: 2
};

Then we know that x and y are populated with the shorthand and foo and bar are defined from scratch within the object.

Only Quote Properties That are Invalid Identifiers

We should only quote properties that are invalid identifiers within our object.

This is because valid identifiers don’t need to be quoted so they’re redundant there.

For instance, if we have the following:

const obj = {
  'x': 1
};

Then we don’t need the quote around the x since x is a valid identifier.

A valid identifier is alphanumeric and can’t start with a digit. It can also have an underscore or dollar sign.

In the other hand, if we have the following code:

const obj = {
  'x-1': 1
};

Then we need quotes around x-1 since x-1 isn’t a valid identifier.

Don’t Call Object.prototype Methods Directly

Object.prototype methods like hasOwnProperty , propertyIsEnumerable , and isPrototypeOf shouldn’t be called on the object itself since it may be shadowed by the properties on the object in question.

Our object may have noninherited properties with the same name, or it might have been created without the Object prototype by calling Object.create(null) .

Therefore, to make sure that we can call those methods, we should write something like the following:

const obj = {
  a: 1
};

const hasA = Object.prototype.hasOwnProperty.call(obj, 'a');

In the code above, we called the hasOwnPrototype object instance method by using the call method on Object.prototype.hasOwnProperty .

The first argument is our obj object which is the value of this that we use in the hasOwnProperty method.

The 2nd argument is the argument that we pass into hasOwnProperty .

We can also cache the method with a constant so that we don’t have to do the lookup for the method every time that we call it.

To do that, we can write the following code:

const obj = {
  a: 1
};
const hasProperty = Object.prototype.hasOwnProperty;
const hasA = hasProperty.call(obj, 'a');

In the code above, we cached Object.prototype.hasOwnProperty by assigning it to the hasProperty constant so that we can just use that to call the method.

Photo by Bimata Prathama on Unsplash

Prefer the Object Spread Operator Over Object.assign to Shallow Copy Objects

The spread operator lets us do a shallow copy and merge objects in a way that’s shorter than calling Object.assign .

For instance, instead of writing the following:

const obj = {
  a: 1
};
const obj1 = {
  b: 1
};

const merged = Object.assign({}, obj, obj1);

In the code above, we merged the obj and obj1 objects into an empty object by calling Object.assign . The first argument has the object that we want to merge into.

Therefore, the merged constant would have the value {a: 1, b: 1} .

To do a shallow copy, we write the following code:

const obj = {
  a: 1
};

const copy = Object.assign({}, obj);

In the code above, we make a shallow copy of obj , which just copies the top-level properties and leave other properties referencing the original object, by putting all the properties if obj into an empty object.

Object.assign is once again is called with the empty object as the first argument, which is the object that we’ll put the copied properties into.

Therefore, copy will have the same properties as obj .

With the spread operator, we can do this in a much shorter way. To merge objects, we write:

const obj = {
  a: 1
};
const obj1 = {
  b: 1
};
const merged = {
  ...obj,
  ...obj1
};

The spread operator ... spreads the properties into the object that it’s in.

To do a shallow copy, we write the following:

const obj = {
  a: 1
};
const copy = {
  ...obj
};

It’s the same thing except that we only have one object.

Conclusion

We should use the spread operator to make shallow copies of objects and merge multiple objects into one.

If we have shorthands like the property shorthand, then we should use it.

Finally, don’t call Object.prototype methods directly since they may not exist for various reasons.

Categories
JavaScript Best Practices

JavaScript Best Practices for Writing More Robust Code — Value Checks

JavaScript is an easy to learn programming language. It’s easy to write programs that run and does something. However, it’s hard to account for all the uses cases and write robust JavaScript code.

In this article, we’ll look at how to do value checks in less bug-prone ways.

Inequalities

We can compare if something isn’t equal with the following operators in JavaScript:

  • > — greater than
  • < — less than
  • <= — less than or equal to
  • >= — greater than or equal to
  • !== , !=— not equal

If we’re checking that something isn’t equal, then we should use the !== operator since it doesn’t do any kind of type coercion before doing the comparison.

We don’t want JavaScript to automatically convert the types for us so that we can we don’t step into traps caused by automatic type conversion.

The rules for automatic type conversion before comparison with != is complex, so we don’t want to deal with them.

With the other operations, there’re no alternatives that don’t do type conversion before comparison.

Therefore, we should be careful with them. Ideally, we convert all the operands to the same type before comparing so no one will be confused about what type of data the operands have.

For instance, the expression 2 > ‘1’ returns true as JavaScript automatically converts the string '1' into number 1.

This may seem convenient, but we can easily step into traps when we have strings that don’t have numbers or strings that have numbers mixed with other text.

Therefore, we should convert them all to the same type before doing any comparison.

In the example above, we can call the Number factory function to convert them both to numbers before comparing them. We can write:

Number(2) > Number('1')

to make sure that they’re both numbers. This is even more important if one or more operands are variables since we can’t see the value of them directly.

The principles above also apply to the < , <= and >= operators.

Checking for the Existence of Values in an Array

We can check for the existence of a value in an array in a few ways. We can use the array instance’s some or indexOf methods.

The some method checks if a given value exists and returns true if it does and false otherwise.

It takes a callback that takes the array entry as the parameter and returns the condition for the item that we’re looking for.

For instance, we can use it as follows:

const arr = [1, 2, 3];
const hasOne = arr.some(a => a === 1);

In the code above, we have an array arr , then passed in a callback to some , which returns a === 1 to specify that we’re looking for an array entry that equals 1 in the arr .

The callback can also take the index of an array itself and the array as the optional 2nd and 3rd parameters respectively.

Therefore, hasOne is true since 1 is in arr .

We can also use indexOf to check if a value is in the given array. It returns the array index of the element if it exists. If the given item isn’t in the array, then it returns -1.

It takes the item we’re looking for and searches for it by using the === operator. For instance, we can write the following code to use it:

const arr = [1, 2, 3];
const index = arr.indexOf(1);

Then index is 0 since 1 is the first entry of arr .

indexOf can also take an optional starting index as the 2nd argument to make it search from that index on.

For instance, if we write:

const arr = [1, 2, 3];
const index = arr.indexOf(1, 1);

We get that index is -1 because we started searching from index 1 to the end of the array, none of which has 1 as the value.

Conclusion

To check for values in an array, we can use the some or indexOf operator.

If we need to use the comparison operators >= , <= , > , or < , then we should convert the types explicitly ourselves if we don’t know what the operands have so that we know that they’ll be the same type when we compare them.

We don’t want to fall in the traps that are caused by automatic type conversions.

Categories
JavaScript Best Practices

JavaScript Best Practices — Arrow Functions and Constructors

JavaScript is a very forgiving language. It’s easy to write code that runs but has mistakes in it.

In this article, we’ll look at arrow functions signatures, spacing, and remembering to call super in a child class constructor.

Arrow Function Arguments

When we define arrow functions, we don’t need parentheses if our function only takes one parameter.

For instance, we can write the following to return something multiplied by 2:

const double = x => x * 2;

In the code above, our double function has a parameter x and return x multiplied by 2.

As we can see, we didn’t have parentheses wrapped around the signature, since it isn’t needed if the arrow function only has one parameter.

The parentheses for an arrow function with only one parameter is optional. We can put it in if we think it makes reading the function clearer. For instance, we can write the following:

const double = (x) => x * 2;

Which is the same as what we have in the previous example.

If our arrow function doesn’t have one parameter, then parentheses are required. For instance, we can write the following functions:

const foo = () => {};
const add = (a, b) => a + b;

In the code above, we have the foo function that has no parameters, so the function signature has to have parentheses wrapped around nothing to indicate that it takes no parameters.

Another example is the add function, which has 2 parameters, so we need parentheses to wrap around the a and b parameters.

Space Before or After an Arrow Function’s Arrow

An arrow function has a fat arrow as part of its function definition. Usually, we have a space character before and after the fat arrow.

For instance, we usually define arrow functions as follows:

const foo = () => {};

In the code above, we have the foo function, which has a space character both before and after the => fat arrow.

This spacing makes our function definition more clear and text that’s spaced out is easier to read than text that has no spaces between them.

Remember to Call super() in Constructors

If we have a class that extends another class in JavaScript, then we’ve to remember to call super so that we won’t get an error when we run our code.

For instance, if we have the following code:

class Animal {
  constructor(type) {
    this.type = type;
  }
}

class Cat extends Animal {
  constructor() {}
}

const cat = new Cat();

Then when we run the code above, we’ll get an error telling us to call the super constructor, something like ‘Uncaught ReferenceError: Must call super constructor in derived class before accessing ‘this’ or returning from derived constructor’.

This is good because we won’t forget to call super in Cat since the code won’t run.

Therefore, we should correct this mistake by writing the following code instead:

class Animal {
  constructor(type) {
    this.type = type;
  }
}

class Cat extends Animal {
  constructor(type) {
    super(type);
  }
}

const cat = new Cat();

In the code above, we called super in the Cat class’s constructor.

Even though JavaScript classes are just syntactic sugar for constructor functions, it does prevent us from making mistakes that are easy to make before we have the class syntax.

We have the extends keyword and the super function instead of calling the call method on the parent constructor to calling the parent constructor in the child constructor using the call method.

As we can see, there’s error checking to stop us from going in the wrong direction by making sure that we call super . Otherwise, the code won’t run.

With the old constructor function syntax, there’s no way to tell if we did anything wrong. Forgetting to call the parent constructor won’t give us any errors with the old syntax. We’ll just get unexpected behavior.

Conclusion

Arrow function signatures may not need parentheses if our arrow function only has one parameter.

Otherwise, if our arrow function has more than one parameter or no parameters, then we need the parentheses.

If we forgot to call super in the constructor in a child class, we’ll get an error, so that we won’t forget to call it since the code won’t run.

This is a great benefit of the class syntax since it has error checking built-in.