Categories
JavaScript Best Practices

Why it’s Time to Stop Using JavaScript IIFEs

In JavaScript speak, IIFE stands for Immediately Invoked Function Expressions.

It’s a function that’s defined and then executed immediately.

In this article, we’ll look at why it’s time to stop writing IIFEs in our code.

We Can Define Block-Scoped Variables in JavaScript

Since ES6 is released as a standard, we can declare block-scoped variables and constants with let and const. It also introduced stand-alone blocks to isolate variables and constants into their own blocks, unavailable to the outside.

For example, we can write:

{
  let x = 1;
}

Then x wouldn’t be available to the outside.

It’s much cleaner than:

(()=>{
  let x = 1;
})();

Now that ES6 is supported in almost all modern browsers, we should stop using IIFEs to separate variables from the outside world.

Another way to isolate variables are modules, which are also widely supported. As long as we don’t export them, they won’t be available to other modules.

We Don’t Need Closures As Much Anymore

Closures are functions that return another function. The returned function may run code that’s outside of it but inside the enclosing function.

For example, it may commit some side effects as follows:

const id = (() => {
  let count = 0;
  return () => {
    ++count;
    return `id_${count}`;
  };
})();

Again, this is more complex and unnecessary now that we have blocks and modules to isolate data.

We can just put all that in their own module, then we won’t have to worry about exposing data.

It also commits side effects, which isn’t good since we should avoid committing side effects whenever possible. This is because they make functions hard to test as they aren’t pure.

Functions that return functions also introduce nesting when we can avoid it and so it’s more confusing than ones that don’t.

The better alternative is to replace it with a module.

With a module, we can write:

let count = 0;

export const id = () => {
  ++this.count;
  return `id_${count}`
}

In the code above, we have the same count declaration and we export the id function so that it can be available to other modules.

This hides count and exposes the function we want like the IIFE, but there’s less nesting and we don’t have to define another function and run it.

Aliasing Variables

Again, we used to write something like this:

window.$ = function foo() {
  // ...
};

(function($) {
  // ...
})(jQuery);

Now we definitely shouldn’t write IIFEs just to create aliases for variables since we can use modules to do this.

With modules, we can import something with a different name.

Today’s way to do that would be to write:

import { $ as jQuery } from "jquery";

const $ = () => {};

Also, we shouldn’t attach new properties to the window object since this pollutes the global scope.

Capturing the Global Object

With globalThis , we don’t have to worry about the name of the global object in different environments since it’s becoming a standard.

Therefore, we don’t need an IIFE to capture the global object by writing the following in the top-level:

(function(global) {
  // ...
})(this);

Even before globalThis , it’s not too hard to set the global object by writing:

const globalObj = self || window || global;

Or if we want to be more precise, we can write:

const getGlobal = () => {
  if (typeof self !== 'undefined') { return self; }
  if (typeof window !== 'undefined') { return window; }
  if (typeof global !== 'undefined') { return global; }
  throw new Error('unable to locate global object');
};

Then we don’t have to add the extra function call and nesting introduced by the IIFE.

Optimization for Minification

With JavaScript modules, we don’t have to segregate code with IIFEs any more so that our files can minify properly.

Webpack, Browserify, Parcel, Rollup, etc., can all deal with modules properly, so we should use them instead to create much cleaner code.

Conclusion

It’s time to stop writing IIFEs in our code. It adds extra function definitions and nesting.

Also, it’s an anachronism from the times before JavaScript modules are introduced and widely used. In 2020, we should use modules and blocks for segregating code.

Block scoped variables are used for keeping variables from being accessible from the outside within a module.

Categories
JavaScript Best Practices

JavaScript Best Practices — Strings and Functions

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 using template strings and the best way to define functions.

Use Template Strings

We should use template strings whenever possible. There’re many benefits to using them.

We can put in JavaScript expressions right inside the string, and we can save single and double quotes for quoting text inside the string.

Also, it can be used to create multiline strings since we can add line breaks by just typing them in rather than adding an extra line break character explicitly to do that.

For instance, we can use template strings as follows:

const name = 'jane';
const greeting = `Hi, ${name}`;

In the code above, we have a template string that has the expression name interpolated in it. We do that by using the ${} as the delimiter for interpolating expressions.

We don’t have any spaces between the interpolation delimiter and the expression itself.

This spacing is good because we already have the delimiter to separate the expression from the rest of the string, so we don’t need more space between the expression and the delimiter.

We can create a multiline string as follows:

const name = 'jane';
const greeting = `Hi,
${name}`;

Then we get:

Hi,
jane

as the value of greeting .

As we can see, all we have to do is type in an extra line break. We didn’t have to type out the escaped line break character to create a line break.

A template string is delimited by backticks, so we can use single and double quotes for quoting text inside the string.

Use Function Expressions Instead of Function Declarations

In JavaScript, there’re 2 ways to define functions. One is function expressions and the other is function declarations.

Function declarations are defined as follows:

function foo() {
  // ...
}

We have the function keyword with the name foo and we didn’t assign it to a variable.

Function declarations are hoisted to the top so they can be referenced anywhere in our code.

Function expressions are defined by creating a function and then assigning it to a variable.

For instance, we can create function expressions as follows:

const bar = function() {
  // ...
}

const baz = () => {
  //...
}

In the code above, we defined traditional and arrow functions and assigned each to a variable.

These aren’t hoisted so they can only be referenced after they’re defined.

Function expressions are better because we don’t have to worry about the confusion that arises when we have to think about hoisting.

Hoisting isn’t good for readability since hoisted functions can be referenced anywhere in our code.

Function expressions also work with all kinds of functions rather than just traditional functions.

We can also put a name in the function, but it’s not very useful since we can’t reference it with the name after it’s been assigned to a variable.

For instance, if we have the following code:

const bar = function foo() {
  // ...
}

Then we have to call the function as bar instead of foo . Therefore the extra name isn’t all that useful.

Wrap Immediately Invoked Function Expressions in Parentheses

Immediately Invoked Function Expressions (IIFEs) are functions that are defined and then run immediately afterward.

They’re useful for encapsulating data in the olden days, but now it’s still useful for creating async functions and calling them immediately.

We should wrap IIFEs in parentheses to make sure that everyone knows that it’s an IIFE.

For instance, we can create an async IIFE as follows:

((async () => {
  const foo = await Promise.resolve(1);
  console.log(foo);
})())

In the code above, we wrapped in our async function in parentheses so that we can call it immediately with the opening and closing parentheses.

Then we wrapped the whole expression in parentheses so everyone knows that it’ll run immediately.

Conclusion

If we create strings, we should use template strings. They let us interpolate expressions in a string and frees single and double quotes for quoting text.

We should define functions as function expressions instead of function declarations so that we can only call them after they’re defined. This way, it’s much easier to read since the flow actually goes in sequence.

IIFEs should be wrapped in parentheses so that we all know that it’s an IIFE.

Categories
JavaScript Best Practices

JavaScript Best Practices — Rest Operator

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 why using the rest operators are better than their older alternatives.

Using Rest Parameters Instead of the arguments Object

Rest parameters are the best way to get all the arguments from a function. It works with all kinds of functions.

Whereas the old arguments object only works with old-style traditional functions.

The rest operator is denoted by the ... symbol in the function argument.

We can use it to put all arguments into an array or just arguments that haven’t been set as values of existing parameters that comes before the rest parameter expression.

For instance, if we have the following function:

const foo = (a, b, ...args) => console.log(a, b, args);

Then when we call it as follows:

foo(1, 2, 3, 4, 5);

We get that a is 1, b is 2, and c is the array [3, 4, 5] .

As we can see, the arguments that haven’t been set as the values of the parameters of the function are all put into an array which we can manipulate easily.

We can also put all arguments into an array by writing the following:

const foo = (...args) => console.log(args);

Then we get that args is [1, 2, 3, 4, 5] when we call it by writing foo(1, 2, 3, 4, 5); .

As we can see, rest parameters works great with arrow functions. It works equally well with traditional functions.

This is much better than what we’re doing before, which is using the arguments .

If we go back to using the arguments , then we have to use traditional functions since arrow functions don’t bind to the arguments object.

For instance, we’ve to define a function as follows to use it:

function foo() {
  console.log(arguments);
}

Then we call it as follows:

foo(1, 2, 3, 4, 5);

We get:

Arguments(5) [1, 2, 3, 4, 5, callee: ƒ, Symbol(Symbol.iterator): ƒ]

in the console log output.

This is because the arguments object isn’t an array. It’s an array-like iterable object.

All we can do is loop through it by its entry using the for loop by its index as we do in the following code:

function foo() {
  for (var i = 0; i < arguments.length; i++) {
    console.log(arguments[i]);
  }
}

As we can see, the arguments object has a length property, so we can loop through the entries by its index by using the brackets notation as we do with arrays.

We can also loop through with the for...of loop since it’s an array-like iterable object. Therefore, we can write the following code:

function foo() {
  for (const a of arguments) {
    console.log(a);
  }
}

However, we can’t do anything with it that an array can do like calling the map or filter method on it.

Most likewise, we’ve to convert the arguments object to an array so we can do something with it. If we want to convert it to an array, then we have to do extra work to convert it to an array so that we can do more with it.

To do that we’ve to call the slice method on an empty and then convert the this that we used in slice to the arguuments object so that it’ll return an array.

For instance, we can write the following code to convert the arguments object to an array:

function foo() {
  const args = [].slice.call(arguments, 0);
  console.log(args);
}

In the code above, we converted the arguments object into an array by calling the array prototype’s slice method with the this value set as arguments so that it’ll return an array.

This works because the slice method loops through the array to do the slicing. As we can see, we can loop through the argument object with a regular loop since it has a length property and we can access its values by its index.

We can also write the following instead of what we have in the previous example:

function foo() {
  const args = Array.prototype.slice.call(arguments, 0);
  console.log(args);
}

It does the same thing in that it calls the slice array instance method, but using call to change the this inside the slice method to the arguments object.

If we come back to modern times, we can also use the spread operator to convert the arguments object into an array as follows:

function foo() {
  const args = [...arguments];
  console.log(args);
}

Conclusion

Rest parameters is a useful feature in modern JavaScript. It lets us get the arguments of a function as an array. It’s much better than the old way with the arguments object since it only works with traditional functions and we’ve to do work to convert it to an array.

Categories
JavaScript Best Practices

JavaScript Best Practices — Function Signature and Arrow Functions

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 how to format long function signatures and the best use of arrow functions.

Format Long Signatures by Putting Each Parameter in a New Line

If our function signature is long, then we should separate our arguments into a new line. For instance, we can write the following code to separate our arguments into their own line:

function foo(
  bar,
  baz,
  qux
) {}

In the code above, we have a foo function with 3 arguments bar , baz , and qux .

We separated each parameter into their own line, with , and a new line separating the parameters.

Likewise, we can do the same thing with a long list of arguments. For example, we can write the following code to put arguments into their own line for function calls:

foo(
  bar,
  baz,
  qux
)

In the code above, we have bar , baz and qux all in their own line. The comma and newline separate the arguments instead of just a comma.

When We Use an Anonymous Function, We Should Use Arrow Function Notation

Arrow functions are a great feature of JavaScript. It lets us define functions in a shorter way, and it doesn’t bind to its own value of this or arguments .

Also, we can return the last expression of the function as its return value if the expression that’s to be returned is in the same line as the function signature.

This is great for callbacks and other kinds of anonymous functions since we don’t have to deal with this and arguments with them most of the time.

For instance, if we call the array instance’s map method, then we need to pass in a callback.

Most of the time, we don’t need to manipulate this in our code, so we can just use arrow functions as callbacks.

For instance, we can write the following code to map our array entries into new values as follows:

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

In the code above, we called map on the array [1, 2, 3] . To do that, we passed in a function which maps the entry to a new value that’s squared of the value of the original entry.

Since the expression we’re returning is in the same line as the function signature and the arrow, it’ll return it without adding the return keyword explicitly.

If we want to return expressions that are more than one line long, then we need to wrap it around parentheses.

For instance, we can write a function to do the following:

const foo = () => ({
  a: 1
})

Then when we call foo , we get that its’ return value is:

{
  a: 1
}

In the function above, we wrapped the object around parentheses so that we return the object.

Arrow functions are much shorter than traditional functions since we don’t need the function keyword in all cases and the return keyword is omitted if the item we return is in the same line as the signature.

If we call the map method with a traditional function, then we have to write the following code:

const arr = [1, 2, 3].map(function(a) {
  return a ** 2
});

As we can see, our callback function now spans 3 lines instead of 1. And we have to type out the function keyword.

With all these benefits that arrow function brings, we should use them whenever we can. As long as we don’t need to reference this or use defines a constructor function, we can use it.

Photo by David Clode on Unsplash

Use Implicit Return for Returning an Expression Without Side Effects

As we can see from the examples in the previous sections, we should skip the braces and the return keyword if we have functions that return something on the first line of an arrow function.

We also should make sure that if an arrow function does an implicit return that it doesn’t commit any side effects.

For instance, given the map call we have in the example above:

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

In the function, we have a => a ** 2 so that we can return implicitly by skipping the braces and return keyword. Also, note that all it does is returning the expression and it’s not modifying anything outside the function.

Conclusion

Long function signatures and function calls should have parameters and arguments separated onto their own line.

Also, we should use arrow functions so that we can benefit from the features that it brings like conciseness and not having to worry about the value of this .

Categories
JavaScript Best Practices

JavaScript Best Practices — Designing Functions

Cleaning up our JavaScript code is easy with default parameters and property shorthands.

In this article, we’ll look at the best practices when designing functions.

Design at the Function Level

We got to design functions properly so that they can be worked on in the future without hassle.

The functions got to have high cohesion. This means that we only want to have relevant code in each function.

Anything unrelated shouldn’t be there.

However, there’re a few kinds of cohesion that aren’t good.

Sequential Cohesion

One of them is sequential cohesion, which means that each operation in a function must be done in a specific order.

We don’t want to get the birth date, then calculate the age and time for retirement afterward for example.

If we have a function that does both, then we should separate them into separate functions.

Communicational Cohesion

Communicational cohesion is another kind of cohesion that isn’t ideal.

Functions that use the same data and aren’t related in any other way shouldn’t be in one function.

For instance, if we have functions that log data and then reset them, then each operation should be in their own function.

Temporal Cohesion

Temporal cohesion is where operations are combined into a routine because they’re all done at the same time.

They encourage us to include code that are unrelated but has to be run at the same time.

In this case, we should separate those unrelated things into their own functions. and then run them under one umbrella function that has to be run at the given time.

For instance, we can write something like the following:

const showSplashScreen = () => {
  //...
}

const readConfig = () => {
  //...
}

const startUp = () => {
  showSplashScreen();
  readConfig();
}

Procedural Cohesion

Procedural cohesion is also bad. It means that the operations in a function has to be done in a specified order.

Things like a function to get a name, address, and phone number aren’t good since they aren’t really related, but they’re run in the same function.

It’s better to separate them out into their own functions and call them when needed.

Logical Cohesion

Logical cohesion is when several operations are put into the same function and they’re selected by a control flag that’s passed in.

Since they aren’t related to each other, we shouldn’t have those operations all in one function.

For instance, if we have:

const showSplashScreen = () => {
  //...
}

const readConfig = () => {
  //...
}

const doSomething = (option) => {
  if (option === 'splash') {
    showSplashScreen();
  } else if (option === 'read-config') {
    readConfig();
  }
}

Then we shouldn’t have the doSomething function.

Coincidental Cohesion

If a function has operations that have no relationship to each other, then that’s coincidental cohesion.

We should separate any code that isn’t related to each other into their own function.

Good Function Names

We got to name functions with good names. There are a few guidelines to following when we’re naming functions.

Describe Everything the Function Does

A function name should describe what the function does. So if it counts the number of apples, then it should be named something like countApple() .

We should have functions that only do one thing and avoid side effects so we don’t have to describe all of them in the name.

Photo by NordWood Themes on Unsplash

Avoid Meaningless or Vague Verbs

We want verbs that describe what the function does, so verbs like perform , process , or dealWith are too vague.

If a function is counting something then it should have the word like count or a synonym in the name.

Don’t Differentiate Function Names Solely by Number

Number names are not good, something like countApples1 , countApples2 , etc. aren’t good.

They don’t distinguish the difference between them by their name.

Make Function Names as Long as Necessary

A function name should be as long as necessary to describe everything that it does.

This way, everyone reading the code will know what a function does from the name.

Use a Description of the Return Value to Name a Function

If a function returns a value, then it should be named for whatever it returns.

So applesCount is good because we know that it returns the count of apples.

Conclusion

When we define functions, we should avoid various kinds of cohesion that don’t contribute to ease of reading and maintenance.

Also, we should name functions with descriptive names that describe everything that they do.