Categories
JavaScript Best Practices

JavaScript Best Practices for Writing More Robust Code — Arrays and Iteration

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 better ways to manipulate arrays and looping through them.

Use the for…of Loop

The for...of loop is a loop that’s introduced with ES2015 to iterate through each entry of an iterable object.

This loop is the best loop for looping through all entries of an iterable object because it works with any kinds of iterable objects, including arrays, the arguments object, maps, sets, and DOM Node lists.

It’s much better than the regular for loop and the while loop because we don’t have to worry about setting the indexes and loop conditions.

All we have to do is to use the for...of loop and reference the object that we want to loop through.

For instance, we can use it to loop through an array as follows:

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

In the code above, we used the for...of loop on the arr array to loop through all the entries of arr .

Another good thing about using for...of is that we can use const to make sure that we can’t change the entry that’s being looped through, which is a .

This is a feature that isn’t available with any other kinds of loops.

We can also loop through other iterable objects like maps as follows:

const map = new Map([
  ['a', 1],
  ['b', 2]
]);
for (const [key, value] of map) {
  console.log(key, value);
}

In the code above, we created a new Map instance. Then we can loop through the map object and extract the key and value with the destructuring syntax as we did above.

The for...of loop is the only kind of JavaScript loop that lets us destructure items right inside the loop.

The destructuring syntax lets us extract the items easily and clearly. Therefore, it’s less error-prone than regular for or while loops as we can do a lot all in one line while retaining the clarity of our code.

Use Array.isArray() to Check If a Variable is an Array

Array.isArray() is the most reliable method to check if a variable or a value is an array.

It’s the most reliable method to determine if something is an array because it works for arrays from different iframes or document objects.

We should use this instead of alternatives like instanceof because of the possibility of having multiple global objects existing.

Multiple iframes and tabs will have multiple Array objects, and their Array.prototype property will all be different. To make sure that we check through all of them, we have to use Array.isArray instead of arr instanceof Array .

Checking the constructor property has the same problem as the instanceof check.

Therefore, we should use Array.isArray to check if a value or variable is an array since it checks all global Array objects to see if it’s an instance of them.

For instance, we can use it as follows:

const foo = [1, 2, 3];
const isArray = Array.isArray(foo);

In the code above, we just called Array.isArray on foo , which returns true if foo is an array and false otherwise.

Therefore, isArray should be true since foo is an array.

Photo by Dušan Smetana on Unsplash

Array Instance’s Map Method

Array instance methods are there for a good reason. They are very useful for manipulating the array instance or returning something derived from the array instance.

The map method lets us convert all the values of the array instance and return a new array with all the existing array instance’s values converted with the callback function that we pass into the map method.

Using map is better than using loops and pushing entries to a new array for example since we write less code to do the same thing.

Therefore, there’s no reason not to use a cleaner way with map than using loops.

For example, we can use it as follows:

const arr = [1, 2, 3];
const doubled = arr.map(x => x * 2);

In the code above, we called map on arr with the callback x => x * 2 to double every entry of arr , put them all in a new array in the same order, and return it.

Therefore, doubled is:

[
  2,
  4,
  6
]

Conclusion

To write robust code that deals with arrays, we should use the for...of loop to loop through all entries of an iterable object.

This way, we don’t have to deal with indexes and loop conditions, and it works with all iterable objects.

Also, the destructuring syntax works with it.

The most reliable way to check if a variable or a value is an array is the Array.isArray method since it works for situations where multiple versions of a global object exist when dealing with iframes.

Finally, the array instance’s map method is the best way to convert all values of an original array to new ones by returning the new one.

Categories
JavaScript Best Practices

JavaScript Best Practices for Writing More Robust Code — Checking Undefined

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 ways to check for undefined and the existence of properties to prevent our JavaScript program from crashing.

Checking for undefined with the typeof Operator

undefined is a value that we often encounter by methods that return undefined or by trying to use properties that don’t exist. Therefore, we should check if some variable is undefined before doing our action.

We can either check for undefined by using the typeof operator or using the === operator.

For instance, we can do that with the typeof operator as follows:

if (typeof foo === 'undefined') {
  //...
}

In the code above, we check if foo is undefined by using the typeof operator on foo and see if it returns 'undefined' .

If it is, then we do something. We can also run something if foo isn’t undefined by writing:

if (typeof foo !== 'undefined') {
  //...
}

This is important because trying to do any operation to something that’s undefined will crash our JavaScript app.

Also, it’s important to check if the property exists by checking whether it’s undefined or not. A property exists if it’s not undefined.

For checking object if an object property exists, we can also use the hasOwnPropety to see if a property exists as a non-inherited property.

We can check if a property exists in an object as follows:

if (typeof foo.bar !== 'undefined' &&
  typeof foo.bar.baz !== 'undefined') {
  //...
}

In the code above, we check if foo.bar exists and if foo.bar.baz exists by checking if both of them aren’t undefined . If the first one isn’t then, we know foo.bar exists, then we can proceed to check if foo.bar.baz exists.

We can’t jump straight into the 2nd expression and just write typeof foo.bar.baz !== ‘undefined’ since foo.bar may not exist. Therefore, it may be undefined , so we must also check if foo.bar exists before doing the 2nd check.

This is critical if we want to do some operation to foo.bar.baz since these properties may not exist.

Object.prototype.hasOwnProperty

To check if a property exists as a non-inherited property in an object, we can also use the hasOwnProperty method in the object instance.

For instance, we can rewrite our property check as follows:

if (foo.hasOwnProperty('bar') &&
  foo.bar.hasOwnProperty('baz')) {
  //...
}

In the code above, we checked is foo.bar exists as a non-inherited property with foo.hasOwnProperty(‘bar’) . Then if foo.bar exists, we check if foo.bar.baz exists by writing foo.bar.hasOwnProperty(‘baz’).

However, if the property is set explicitly to undefined , hasOwnProperty still returns true , so if we probably still need to check if the property is set explicitly set to undefined even if we use hasOwnProperty.

Therefore, typeof is probably more reliable for checking for undefined since it works whether undefined is implicit, which is when the property doesn’t exist, or when it does exist and set to undefined explicitly.

=== Operator

We can also just use the === operator to check for undefined . For instance, we can just do a direct comparison with the === operator to check for undefined as follows:

if (foo.bar !== undefined) {
  //...
}

The code above also works since === doesn’t do any data type coercion before doing any comparison.

Object.is

Lastly, we can use the Object.is method to check for undefined . It takes 2 arguments, which are the items that we want to compare.

Object.is different from === as === +0 and -0 are considered different in Object.is and which isn’t the case with === . Also, NaN is considered the same as itself with Object.is.

However, for comparing undefined , there’s no difference between Object.is and ===.

For instance, we can use Object.is as follows to check for undefined:

if (Object.is(foo.bar, undefined)) {
  //...
}

The code above checks if foo.bar is undefined or if foo.bar exists as we did with the === operator.

Conclusion

There’re many ways to check if something is undefined in JavaScript. One way is to use the typeof operator to check if something has type 'undefined'.

Also, we can use the === operator to directly compare if something is undefined . Likewise, we can use the Object.is to check for undefined.

To check if a property exists in an object, we can use the object instance’s hasOwnProperty method. However, this doesn’t work if the property is set explicitly to undefined since it exists and it’s set to undefined.

Categories
JavaScript Best Practices

JavaScript Best Practices for Writing More Robust Code — More Ways to Find Items

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 ways to find items in JavaScript arrays.

Finding If Something Exists in an Array Instance With the some Method

The JavaScript some method lets us add a check if one or more items with the given condition exists in the array instance.

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

For instance, if we want to check if one more entry in the array instance is even, we use some to do that as follows:

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

In the code above, we have the arr array, which has one even number which is 2.

Then we called some on it with the callback a => a % 2 === 0 to check if each entry is even, where a is the array entry that’s being checked.

In this case, if some finds an array entry that’s even, which there is, then it returns true . Otherwise, it returns false .

Therefore, some should return true .

The callback can also take the index of the array entry that’s being checked as the 2nd parameter, and the array that’s being run on in as the 3rd parameter. They’re both optional.

Therefore, we can rewrite our example as follows:

const arr = [1, 2, 3];
const result = arr.some((a, index, array) => array[index] % 2 === 0);

And we get the same result as before.

some can optionally take a 2nd argument, which is the value of this that we want to reference in our callback function.

We can pass in our own value of this as follows:

const arr = [1, 2, 3];
const result = arr.some(function(a) {
  return a > this.min;
}, {
  min: 1
});

In the code above, we pass in a 2nd argument, which is the object { min: 1 } .

Then that’ll be the value of this in our callback, so we can use its min property to check if there’re some entries of the array that’s bigger than 1.

Since we also use this in the callback, we have to use a traditional function to reference the value of this .

Then result should be true since there are entries in arr that’s bigger than 1.

This is more robust than looping through the array ourselves and checking for each entry with a loop as it’s well tested and used frequently, so the possibility of any bugs with this method is almost zero.

Photo by Ramesh Casper on Unsplash

find

The array instance’s find method lets us find the first entry in the array that meets the given condition.

It always searches from the start to the end of the array. find takes callback with the array entry as the first parameter of the callback and returns the condition of the array entry that we’re looking for in the array instance.

For instance, we can use it as follows:

const arr = [1, 2, 3];
const result = arr.find(a => a > 1);

In the code above, we have the find method which takes a callback a => a > 1 to find the first item in arr that’s bigger than 1.

a is the array entry that’s being looped through.

Then we should get 2 returned since that’s the first entry in arr from the start that’s bigger than 1.

The callback can also take an index of the array instance that’s being looped through as the 2nd parameter and the array instance as the 3rd parameter. However, they’re both optional.

We can use them as follows:

const arr = [1, 2, 3];
const result = arr.find((a, index, array) => array[index] > 1);

In the code above, we retrieved the entry being checked by using the index to access the array entry instead of getting it from the parameter itself.

So we should get the same result as before.

Like some , the 2nd argument of the find method is the value of this that we want to reference in our callback.

For instance, we can pass in an object and set it as the value of this in the callback as follows:

const arr = [1, 2, 3];
const result = arr.find(function(a) {
  return a > this.min
}, {
  min: 1
});

In the code above, we passed in { min: 1 } as the 2nd argument of find . Then we accessed the min property of the object in the callback by referencing this.min .

Therefore, we should see the 2 as the value of result since this.min is 1 and we’re checking a to see if it’s bigger than 1.

Again, this is an array instance method, so it’s less likely there’re bugs in the find method than writing our code if we want to find an item in an array.

Conclusion

The array instance’s some method lets us check if one or more entry of an array has an item with the given condition.

An array’s find method lets us find the first array entry that meets the given condition.

Categories
JavaScript Best Practices

JavaScript Best Practices — Declaring and Using Variables

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

In this article, we’ll look at best practices for declaring and using JavaScript variables.

Implicit Declarations

In JavaScript, if strict mode is off, then we can implicitly declare variables. We can reference variables without declaring it if it’s off, which isn’t good.

For instance, we can write:

foo = 1;

with strict mode off. This will declare a global variable foo , which can be accessed anywhere.

This isn’t good since it’s declared without using doing it and it’s global.

So we should turn on the strict mode in scripts as it’s a hazardous feature to use.

Declare All Variables with let or const

We should always declare all variables with let or const .

Use let for variables and const for constants.

const constants can’t be reassigned to a new value after it’s declared and we must set a value when we declare it.

For instance, we can write:

let x = 1;  
const y = 2;

We can also write:

let x;

Use Naming Conventions

Naming conventions for common suffixes o that we don’t use variables when only need one.

If we use Num as a suffix, then stick with that for numbers, for example.

Check Variable Names

We should check variables as they’re listed in editors and IDEs. Then we can remove variables that aren’t used.

Guidelines for Initializing Variables

Improper data initialization is a big source of problems in computer programs.

If we initialize them properly, we can save lots of debugging time.

If a variable has never been assigned a value, then we should assign one.

If it has an outdated value, then we need to update it.

If part of it has been assigned and another part isn’t then we need to set that part.

We can do that by setting properties or adding to arrays.

Initialize Each Variable as it’s Declared

We don’t have to set a value for let variables when we declare them, but we should set it since we’ll probably forget later.

Also, they should be near where they’re used since we may forget to use them if we don’t.

It also creates the impression that the variable is used throughout the code, which isn’t desirable.

Ideally, Declare and Define Each Variable Close to Where it’s First Used

This make us only declare variables when they’re needed.

It also let people know that the variable isn’t used throughout the code.

Photo by Tim Cooper on Unsplash

Use const When Possible

If we use const , then we can’t assign it to a new value.

However, we can still mutate the object inside.

Pay Special Attention to Counters and Accumulators

If we have counters and accumulators, then we should remember to reset them before they’re used again if necessary.

Initialize a Class’s Member Data in its Constructor

We should initialize all class’s instance variables in the constructor so that they’re ready to use anywhere.

For instance, we can write:

class Person {  
  constructor(name, age) {  
    this.name = name;  
    this.age = age;  
  }  
}

This makes this.name and this.age defined in all methods in the class.

Check the need for Reinitialization

If the value of a variable needs to be initialized, then we should use let . Otherwise, we use const .

Initialize Named Constants Once; Initialize Variables with Executable Code

We should declare named constants with const so that they can’t be reassigned to a new value.

If we have variables, they should be declared with let or const before the code that uses it in a function so that we can reinitialize it as the function is called.

Use Linter Setting that Automatically Initializes All Variables

We can use a linter to check that all variables are initialized.

This makes the process automatic so that we can avoid errors.

Take Advantage of Our Linter’s Warning Messages

Linters like ESLint has lots of rules that we can check to make sure that we’re declaring variables properly.

Therefore, we should take advantage of them so that we can fix improper variable declarations automatically when detected.

Conclusion

We should declare variables properly. It’s easy to do with a linter.

Implicit declarations are bad as they’re global. And we should use let and const to declare them instead.

Strict mode prevents implicit variable declarations.

Categories
JavaScript Best Practices

JavaScript Best Practices for Writing More Robust Code — Finding Items

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 more reliable ways to filter and check for items in arrays.

Check to See If Something Exists in All Entries of an Array With the every Method

The JavaScript array instance’s every method lets us easily check if something exists in all entries of an array.

All we have to do is to pass in a callback with the condition we want to check for in each entry.

For instance, if we want to check if every number in the array is even, we can write the following code:

const arr = [2, 4, 6];
const allEven = arr.every(a => a % 2 === 0);

In the code above, we have the arr array with all even numbers. Then we used every that has a callback with the array entry a as the parameter and we return a % 2 === 0 to check if all numbers in the array are even.

Since they’re all even, allEven is true as every returns true if every entry in the array instance meets the condition given in the callback and false otherwise.

This is more reliable than writing our own loops since it’s shorter and well-tested. Therefore, there’s less chance for bugs.

The callback can also take other parameters. The index that’s being looped through is the 2nd parameter and the array itself if the third. They’re both optional. However, if we need it, then we can include them.

For instance, we can rewrite our example as follows:

const arr = [2, 4, 6];
const allEven = arr.every((a, index, array) => array[index] % 2 === 0);

The every method also takes an object that we can set as the value of this in the callback, if we need to reference this in the callback function.

For instance, we can write the following code to set the value of this and use it inside the callback:

const arr = [1, 2, 3];
const allEven = arr.every(function(a){
 return a >= this.min;
}, { min: 2 });

In the code above, we set the value of this in the callback by passing in { min: 2 } as the 2nd argument.

Then we switched our function into a traditional function so that we can reference the this value in the callback. In the callback, we checked that if each array entry is bigger than or equal than this.min , which is 2.

We don’t have to worry about how to set up our loops and when to end the loop and other things that come with the loop.

Creating an Array With Filtered Entries With the filter Method

The array instance’s filter method returns an array with the entries of an array that has the given condition in the callback included the returned array.

For instance, we can use it as follows:

const arr = [1, 2, 3];
const result = arr.filter(a => a > 1);

In the code above, we called filter on the array instance with the callback a => a > 1 to return a new array with all the entries in arr that’s bigger than 1.

Therefore, we should get [2, 3] as the value of result .

Like every , the callback can also take an optional index and array parameter. index is the 2nd parameter, and array is the 3rd parameter.

So we can also write the following code:

const arr = [1, 2, 3];
const result = arr.filter((a, index, array) => array[index] > 1);

In the code above, we used the array and index instead to reference the entries and instead of using the first parameter a to reference each entry.

Therefore, we should get the same result as before.

This is better than writing our loops since it comes with JavaScript’s standard library, so it’s been well tested to eliminate any bugs.

Also, the algorithm it uses for doing the filtering is guaranteed to be fast enough for production use since it’s in the standard library.

Finally, it’s also shorter than writing our own loops to do the same thing.

Conclusion

The array instance’s every method is great for checking is every entry has something we’re looking for.

To create a new array with the entries in the array instance that meets the given condition, we can use the array instance’s filter method to make that easy.