This page looks best with JavaScript enabled

Class Methods and Comma in Javascript

 ·   ·  ☕ 2 min read

Where does a comma fit in the class methods? No where. Where do I remember it from, then - Vue objects.

When I started using Vue full time some time in 2017, I had this problem with putting commas everywhere. These were becoming like issues with semicolons - except that VS Code Prettier takes care of my semi-colons. Back to classes and commas - we will get back to Vue in a bit.

Head over to a quick refresher on Javascript classes

Why are we even talking about commas?

When you create a class, you just write this -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Account {
  getAccount(id) {
    console.log("got id");
    return 1;
  }

  updateAccount(id) {
    console.log("updated id");
    return id;
  }

  deleteAccount(id) {
    console.log("deleted id");
    return id;
  }
}

Simple enough. These are methods in a class and are not expected to have commas or semicolons between them. So far so good.

Then I fall in love with Vue. I write <script> tags like this -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<script>
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";


export default {
    methods: {
    ...mapActions("accounts", ["getMeAccounts", "insertAccount"]),

    saveRecord() {
      this.createOrUpdateAccount();
    },

    printRecord() {
      this.fetchPrintDetail();
      this.detailDialog = true;
    }
}
</script>

Notice anything strange? Well, they are methods. But they are also in an object called methods. So, it is only natural that we separate the contents of an object using methods.

More often than I would like to admit, I was either not putting commas in Vue, or catching myself putting commas in Controllers of a server (which are classes).

Fix

Use VS Code and use Prettier.

I talk about how I use prettier to format code and how that has saved this universe many times over. Prettier automatically formats code and also puts semi-colons.

However, if there is a problem - say, I introduced a comma where there shouldn’t be any, no formatting is done. This is sure shot way of telling me what’s wrong immediately rather than wait for the compiler or runtime failures.

In fact, I deliberately avoid a semi-colon, or a space just to ensure my linting goes through just fine and Prettier formats the code.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things