Categories
JavaScript Best Practices

JavaScript Best Practices — Numbers, Bad Features, and Conditionals

Spread the love

Like any kind of apps, JavaScript apps also have to be written well. Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some best practices we should follow when manipulating numbers and conditionals.

We also look at bad JavaScript features we shouldn’t use.

Use break to Prevent Fallthrough in switch Cases

We should add break in the end of each case block or statement to prevent cases below the matching case from running.

Therefore, instead of writing:

switch (val) {
  case 1:
    foo()
  case 2:
    bar()
}

We write:

switch (val) {
  case 1:
    foo();
    break;
  case 2:
    bar();
    break;
}

No Floating Decimals

We should start with a 0 in a decimal number if we want to write a decimal between 0 and 1.

It makes everyone clear that it’s a decimal number even though it’s not required by JavaScript.

For example, instead of writing:

const tax = .5;

We write:

const tax = 0.5;

No Reassignment to Function Declarations

We shouldn’t reassign values to function declarations. Overwriting the value of a function declaration is often a mistake or an issue. If we want to be able to change the value, we should use a function expression.

For example, we shouldn’t write:

function foo () { };
foo = otherFunc;

Don’t Assign a Value to Global Variables

Global variables like window and process are for using. We don’t want to reassign a value to it since it’ll overwrite the object and we won’t get any properties in it that we need anymore.

Therefore, we shouldn’t write code like:

window = {};

No Implied eval Calls

Other than eval , there are the Function constructor, setTimeout , and setInterval which also take strings and run them as code.

For instance, we can write:

const fn = new Function('a', 'console.log(a)');

or:

setTimeout('console.log("foo")')

or:

setTimeout('console.log("foo")', 2000)

which are all valid and result in the code in the string being run. It’s a security risk since we can run code from a string. The code in a string is very hard to debug. Also, they can’t be optimized since they’re in a string.

Therefore, we should just write the code.

For instance, we can write:

setTimeout(() => console.log("foo"), 2000)

No Function Declarations in Nested Blocks

Function declarations are supposed to be at the top level only.

JavaScript tolerates it inside a block, but it shouldn’t be there.

Therefore, we shouldn’t have code like:

if (authenticated) {
  function doSomething () {}
}

No Invalid Regex Inside Regex Strings in RexExp Constructors

When we’re using the RegExp constructor to create regexes, make sure that we have valid regex inside the string.

So we shouldn’t write:

const re =new RegExp('[a-z');

but we should write:

const re =new RegExp('[a-z]');

No Irregular Whitespace

We should use normal whitespace characters in our code to avoid issues with parsing it in different runtime environments.

So we shouldn’t have things like:

function foo () /*<NBSP>*/{}

Don’t Use iterator

The __iterator__ property isn’t a standard property in JavaScript objects are creating iterator functions.

Instead, we should use the Symbol.iterator property instead.

So we shouldn’t write something like:

Foo.prototype.__iterator__ = function () {}

Instead, we should write:

const obj = {
  *[Symbol.iterator](){
    //...
  }
}

or:

class Foo {
  *[Symbol.iterator](){
    //...
  }
}

No Labels that Share a Name with an in Scope Variable

We shouldn’t have labels for a loop that shares the same name as a variable inside the loop’s scope.

This causes confusion for both the interpreter and us.

So we shouldn’t write:

let score = 100;
const foo = () => {
  score: while (true) {
    score -= 10;
    if (score > 0) continue score;
    break;
  }
}

No Label Statements

Label statements are labeling loops with a name so we can do some loop operations with it like continue and break .

It’s a rarely used feature in JavaScript.

Therefore, we probably don’t want to use it.

So we shouldn’t have things like:

label:
  while (true) {
    break label
  }

No Unnecessary Nested Blocks

We shouldn’t have nested blocks that are useless.

Nested code is harder to read and useless nesting it’s worse.

So instead of writing:

function foo () {
  {
    bar()
  }
}

We write:

function foo  () {
  bar();
}

Conclusion

We should avoid nonstandard and rarely used constructs.

Also, we shouldn’t have unnecessary code that causes confusion.

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 *