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.

Categories
JavaScript Best Practices

JavaScript Best Practices — Variables

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 define and use variables in our JavaScript code.

Always Use const or let to Declare Variables

We should use let and const to declare variables and constants respectively.

This way, we get block-scoped variables and constants so we won’t run into issues with variables or constants being accessed in places that we won’t expect.

Without strict mode on, using let and const will also stop us from creating global variables.

Global variables pollute the global namespace and the more complex our code is, the more likely that our global variables will have the same name in different places. Then unexpected behavior will occur because of that.

const also prevents us from the reassignment of its value after it’s set. Both let and const prevents us from declaring a variable with the same name twice.

For instance, we can declare variables and constants with let and const as follows:

let a = 1;
const b = 2;

In the code above, we declared a variable a with let and a constant b .

Then we don’t have to worry about them being declared somewhere else or in the case of b , its value being reassigned to something else.

Use One const or let declaration Per Variable or Assignment

We should put each of our let and const declarations in their own line.

For instance, instead of writing the following code to declare multiple variables in one line:

const a = 1,
  b = 2,
  c = 3;

We should instead put the const keyword in front of every declaration as follows:

const a = 1;
const b = 2;
const c = 3;

This way, we know that every line in the code above is declared with const . In the first example, we aren’t sure how they’re declared.

Also, it’s easier to swap variables that are in their own line since we can cut or copy and paste the whole line.

We can also step through each line with the debugger instead of looking at all the declarations at once.

Group All consts Declarations Together and Then Group All let Declarations Together

We should group all the const declarations together and then group all the let declarations together.

If we scatter them everywhere, then we’ll have a problem finding them later.

Also, we might need to assign a variable depending on one of the previously assigned variables.

For instance, if we have the following code:

const a = 1;
let foo;
const b = 2;
let bar;
const c = 3;

Then it’s hard to read and trace which variable is assigned to what. Instead, we should write the following:

const a = 1;
const b = 2;
const c = 3;

let foo;
let bar;

which is much more organized.

Photo by John Duncan on Unsplash

Assign Variables Where We Need Them But Place Them in a Reasonable Place

We should assign variables where we need since let and const variables are block-scoped and what those are the variables and constants that we should have.

Variables declared with var are function scoped and are hoisted so they can be accessed in places that we may not expect them to be accessed.

For instance, we should place our variables as follows:

const getGreeting = () => 'hi';

const greet = (name) => {
  if (!name) {
    return '';
  }

  const greeting = getGreeting();
  return `${greeting} ${name}`;
}

In the code above, we have the greeting constant inside our greet function. We put it there so we don’t have to run the getGreeting function unnecessarily.

We only run the getGreeting function when the name is a truthy value so that we don’t have to run it on every call.

Therefore, we didn’t place the code for the greeting declaration at the top line of or greet function as follows:

const getGreeting = () => 'hi';

const greet = (name) => {
  const greeting = getGreeting();
  if (!name) {
    return '';
  }

  return `${greeting} ${name}`;
}

It’s more efficient to declare variables and constants only when we need to use them.

Conclusion

When we declare variables, we should always use let or const to only declare block-scoped variables and constants.

const and let variables should be grouped in their own group. Also, they should be declared only when they’re needed.